JavaScript generates an image and its corresponding answer at random

I am currently working with the following code:

<!DOCTYPE html>
<html>
<head>

<script language="JavaScript">
<!-- Hide from old browsers


function pickimg(){
var imagenumber = 5 ;
var randomnumber = Math.random() ;
var rand1 = Math.round( (imagenumber-1) * randomnumber) + 1;
images = new Array
images[1] = "1.png"
images[2] = "2.png"
images[3] = "3.png"
images[4] = "4.png"
images[5] = "5.png"
var image = images[rand1]
document.randimg.src = image
}
// -- End Hiding Here -->
</script>

</head>


<body onLoad="pickimg()">

<a href="" onClick="pickimg();return false;"><IMG SRC="YOUR IMAGE" name="randimg" border=0></a>


</body>
</html>

This piece of code allows me to display a random image and change it when clicked. These images represent math questions, and I also want to include answer images (answer1.png, answer2.png ... answer5.png).

My goal is the following:

  1. When entering the webpage, a random question image should be displayed.

  2. Upon clicking on the question image, the corresponding answer image should appear. For example, if the random question image is 1.png, then the answer1.png should be shown.

  3. If the user clicks on the answer1.png image, another random question image followed by its answer should be displayed. This sequence should continue without repeating questions until all are displayed, and then a new random sequence of 5 images and answers should begin.

Thank you for your assistance!

Alternatively, I could use different webpages with links instead of images, but the process of ensuring no repetition would be more complicated. What do you suggest?

Answer №1

If you're looking for a solution, one option is to shuffle your array by following the guidelines provided in this article on shuffling JavaScript arrays. Once shuffled, you can easily loop through the randomized elements.

Answer №2

Received some assistance with this code and it is functioning perfectly.

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <title></title>
 <base href="http://www.vicsjavascripts.org/StdImages/" />
</head>

<body>
<img id="question" src="1.gif" style="visibility:hidden;" onclick="Question('question','answer',QAArray,false);"/> 
<br/>
<img id="answer" src="Egypt5.jpg"  style="visibility:hidden;"onclick="Question('question','answer',QAArray,true);" />

<script type="text/javascript">
/*<![CDATA[*/

var QAArray=[
 ['1.gif','Egypt5.jpg'],
 ['2.gif','Egypt6.jpg'],
 ['3.gif','Egypt7.jpg'],
 ['4.gif','Egypt8.jpg']

]

function Question(q,a,ary,qa){
 var qo=document.getElementById(q),ao=document.getElementById(a),o=Question[a];
 if (!o||!o.a[0]){
  Question[a]=o={
   a:ary.concat().sort(function(){return 0.5 - Math.random();})
  }
 }
 if (o&&o.a[0]){
  if (qo.style.visibility=='hidden'){
   qo.style.visibility='visible';
   qo.src=o.a[0][0];
   ao.src=o.a[0][1];
  }
  if (qa===false&&ao.style.visibility=='hidden'){
   ao.style.visibility='visible';
  }
  else if (qa===true){
   qo.style.visibility=ao.style.visibility='hidden';
   o.a.splice(0,1);
   Question(q,a,ary);
  }
 }

}

Question('question','answer',QAArray);

/*]]>*/
</script>
</body>

</html>

Answer №3

To mix up the elements of an array, you can utilize the sort() method in JavaScript.

let myArray = [10, 20, 30, 40, 50, 60, 70];
myArray.sort(() => Math.random() - 0.5);
console.log(myArray);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered a network error: A rogue token < was found in JSON at position 0 within a new Apollo

https://i.sstatic.net/D25ai.png const httpLink = createHttpLink({ uri: 'http://localhost:3090/' }) const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache() }) client.query({ query: gql` query users { ...

ASP updatePanels causing scrollable grid plugin offsetWidth to be undefined

I am attempting to create scrollable gridviews within update panels by utilizing a function that is called in the pageLoad() function LoadScrollPopupOverridesBehavior() { $('.GridViewPopupWithOverride').Scrollable({ ScrollHeight: 350 ...

Learn the steps to export a constant value in Next.js using React!

I need to export the constant value views from BlogPost.js to blog.js. This is the content of BlogPost.js: import React from 'react'; import useSWR from 'swr'; import format from 'comma-number'; import { useColorMode, He ...

Spin a sphere by clicking on a link using three.js

I've designed a spherical object and have a group of links. I'm looking for a way to manipulate the position or rotation of the sphere by simply clicking on one of the links. Despite extensive searching, I haven't been able to find an exampl ...

What causes the .getJSON function to return a MIME type error when trying to access the API

I've been attempting to make a call to the Forismatic API, but I keep encountering a MIME type error when sending it. JQuery Request: $(document).ready(function() { $("#quote-button").on("click", function(){ $.getJSON("https://api.forism ...

Tips for utilizing the .clone() method within a loop or for each individual element of an array

Due to certain requirements, I find myself in a situation where I need to customize the invoice template within the software I use. The invoices are generated in HTML format, prompting me to consider utilizing Stylish and Grease Monkey for this task since ...

Issue encountered in Vite Preview: Uncaught (in promise) SyntaxError: JSON.parse found an unexpected character at the beginning of the JSON data, line 1 column 1

Encountering the error message Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data when running vite preview after running vite build. https://i.sstatic.net/61Y9t.png Here is my vite.config.js: import { ...

Rotating objects in Three.js: Aligning with a target point and orienting towards another location

I'm a beginner when it comes to three.js and 3d programming, so forgive me if this question sounds basic. I'm hoping for an answer that can help me grasp the core concepts. Currently, I have an object that needs to face another point (in this ca ...

How to prevent v-menu from overlapping a navbar in Vue.js

Exploring the examples on the main page of Vuetify, we come across the v-menu component showcased in detail. Check it out here: https://vuetifyjs.com/en/components/menus/#accessibility If you activate any of the buttons to open the v-menu and then scroll ...

Generating a constantly evolving 3D model and keeping it current within a web browser

My website already has a large user base, and I am looking to create a 3D visual representation of data on one of the pages. This model needs to be easily updatable based on each user's database information (imagine a square board with a ball whose po ...

Unusual Vue syntax: deconstructing `state` from `this.$store` with a default value of an

While working on a pre-existing project, I came across some interesting notation in a Vue project utilizing Vuex: const { state = {} } = this.$store; const { orders = {} } = state; This code snippet appears to be creating a local object named "state" tha ...

Creating dynamic image carousels using the latest versions of Bootstrap and AngularJS

I have created an array that stores various images using angularJS: $scope.docImg = [ '../../Content/Image/BackGrounds/abra.png', '../../Content/Image/BackGrounds/background_black.jpg', '../../Content/I ...

Puppeteer is unable to detect the node.js handlebars helpers

I'm utilizing puppeteer in NodeJs to generate a PDF file. I use handlebars to render the template and pass variables during compilation for handlebars to access them. Here is the current code snippet: const browser = await puppeteer.launch({ he ...

It seems that the maximum call stack size has been exceeded, resulting in a

Within this dropdown, I have incorporated a checkbox containing values in the form of an object. (refer to attached image) Every time I make a selection from the dropdown, there is a watch function that updates this new value, which is essentially an arra ...

Require assistance with refreshing the index for the chosen row

I have encountered a problem while attempting to manipulate table rows using Javascript. Adding new rows works fine, but deleting rows presents an issue. Specifically, the delete function fails if the first row or a row in the middle is deleted (the live ...

I'm having trouble figuring out why this React Router setup is not functioning properly. Can anyone provide any insights

As I delve into react routing practice, I've put together a geography-based web app. Starting off, I configured the router paths: import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { BrowserRo ...

Vietnamese special characters are not supported in JSON on Windows Phone 8.1 when using IBM Mobile First

In my IBM mobile first application, I am facing an issue with JSON response containing Vietnamese characters (e.g. Tôi là một nhân vật đặc biệt) on Windows 8.1 Phone. The character encoding I am using is UTF-8. resourceRequest.send($scope.dat ...

Guide on incorporating a dropdown menu within a Jssor slider

I am facing an issue with trying to include a dropdown menu inside the Jssor slider. The menu does not drop down when placed inside it. Here is the code snippet: <head> <script src="jquery.js"></script> <script src="jssor.slider.min. ...

The onClick() handler within the map function is erroneously altering the state of every element rather than just the element that was clicked

Currently, I am working on a Next.js website that focuses on multiple choice questions (MCQs) and answers. Initially, only the questions are displayed with the title and options. There is a feature where a button allows users to reveal the answer to a sp ...

Embed a stackoverflow.com iframe within a jsbin

While exploring code using jsbin, I mistakenly linked the iframe to . When my work in loads, it triggers an alert that redirects back to . I am unable to figure out how to modify my jsbin code. Is there a solution or should I start from scratch? ...