Choose three different images and one corresponding word from a JavaScript array to be displayed individually on the screen in separate div containers

I am in the process of developing a web game that will showcase 3 images on the screen, and the player must select the image that corresponds to the displayed word. I have successfully created a JavaScript array containing the images and words retrieved from a database, and I have successfully displayed 3 random images from the array in separate divs on the screen.

However, I am currently facing difficulties in displaying the word simultaneously with the 3 images, which corresponds to one of the randomly displayed images. Below is my current code:

 <script>
  var items = [
  <?php
  $con = mysql_connect("localhost","*****","******");
  if (!$con) {
    die('Could not connect: ' . mysql_error());
  }
  mysql_select_db("learning_game", $con);
  $result = mysql_query("SELECT * FROM data");
  $first = true;

  while ($row = mysql_fetch_array($result)) {
    if (!$first) {
      echo ",";
    }
    $first = false;
    echo "{name:'" . $row['word'] . "',image:'" . $row['image'] ."'}";
}
  mysql_close($con);
  ?>    
  ];

for (var i = 0; i < items.length; i++) {

}  

   document.write("<br /> <br /> <br />");

 console.log(items);
 top.items = items;

 var images = new Array();
  var list = document.getElementsByTagName('div')[0];

   for(i = 0; i < 3; i++) {

       // Choose a random item and remove it from the array
       var item = items.splice(Math.floor(Math.random() * items.length), 1)[0];

      // Create the image element and set its src attribute
       images[i] = document.createElement('img');
        images[i].src = item.image;

      // Add it to your container element

   }

 document.getElementById("one").appendChild(images[0]);
 document.getElementById("two").appendChild(images[1]);
 document.getElementById("three").appendChild(images[2]);

     </script>

I aim to have a total of 4 divs - one div per image and the last div for the word corresponding to one of the images. The JavaScript Array content is as follows:

var items = [
{name:'Coch',image:'upload/coch.png'},
{name:'Glas',image:'upload/glas.png'},
{name:'Melyn',image:'upload/melyn.png'},{name:'Ci',image:'upload/dog.jpg'},
{name:'Cath',image:'upload/cath.jpg'},{name:'Gwyrdd',image:'upload/gwyrdd.png'},
{name:'Un',image:'upload/un.jpg'},{name:'Dau',image:'upload/dau.jpg'},
{name:'Tri',image:'upload/tri.jpg'},{name:'Bochdew',image:'upload/bochdew.jpg'},
{name:'Piws',image:'upload/piws.png'}];

'Name' signifies the word, and 'image' provides the link to the image in the filesystem.

I would greatly appreciate any assistance. Thank you in anticipation.

Answer №1

Instead of relying on splice to modify the original array, why not keep track of the index of the randomly-selected item in a separate array (ensuring it hasn't been selected before)?

Additionally, rather than using individual containers for each image, consider letting them flow consecutively (though I'm unsure of your end goal here).

Check out this function that showcases this approach. Take a look at it in action on JS Fiddle or interact with the full-screen result here.

(My apologies for utilizing jQuery which may not align with your preferences; it was just easier for me to provide you with a functioning demonstration using a library.)

function imageReset() {
   var selected, img,
      imageContainer = $('#images').empty();
   currentImages = [];
   while (currentImages.length < 3) {
      selected = Math.floor(Math.random() * items.length);
      if (currentImages.indexOf(selected) === -1) {
         currentImages.push(selected);
      }
   }
   selectedImage = currentImages[Math.floor(Math.random() * 3)];
   $('#word').empty().html(items[selectedImage].name);
   $.each(currentImages, function(i, imageIndex) {
       img = $('<img>').attr({
           src: items[imageIndex].image,
           width: "200",
           height: "200"
       });
       if (imageIndex === selectedImage) {
          img.data('correct', true);
       }
       img.appendTo(imageContainer).on('click', imageClick);
   });
}

Here's a sneak peek of how the final page will appear:

http://jsfiddle.net/ErikE/zN93u/embedded/result/

Some insights about avoiding libraries:

  • The challenging aspect is determining if the correct image was clicked. You can achieve this by using an expando attribute like "data-correct," although this method may pose cross-browser obstacles. I employed jQuery's data storage via data(). Alternatively, without marking any image as special, you can inspect the 'src' of the image itself and then search through the currentImages array to identify the correct one.
  • $.each() iterates through an array. A traditional loop like
    for (i = 0, l = arr.length; i < l; i += 1) {}
    works fine too.
  • empty() clears all contents of an element. You could alternatively remove the first child repeatedly until no children remain.
  • $('<img>') functions similarly to createElement('img').

I strongly advise using a library. There's really no compelling reason to avoid one except personal choice. Even when employing a library, you can still grasp pure JavaScript techniques by studying the underlying code. If I were running a software development company, I would actually mandate my junior JavaScript developers to utilize a library due to the substantial increase in coding efficiency and quality. While they should eventually become adept in the "traditional" way, initially it's best not to waste time reinventing the wheel.

Answer №2

To simplify the process, start by creating a new array called participants and store three names in it when selecting your images. Utilize the same randomization method to choose one of these names.


var participants = new Array()
…
    images[i].src = item.image;
    participants[i] = item.name;
…
var selected_name = participants[Math.floor(Math.random() * 3)];

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

Changing the background color of .pane and .view elements in an Ionic web application using JavaScript

Looking to modify the background-color of two css selectors, .pane and .view, that are located within the ionic.css file. Despite multiple attempts to do so using JavaScript directly in the index.html file, the changes are not reflected. The code snippet ...

Stopping a Bootstrap Modal Closure When Validation Errors are Present

I'm dealing with a bootstrap model within a .NET MVC5 app. Although my client-side validation is functioning properly (using jquery unobtrusive in MVC), I have encountered an issue where the modal keeps closing even when there are errors present. How ...

How can you call a function in ExpressJS that is located in a different file?

I am having trouble with my UserController and database configuration file db.js. I am trying to make a function in the UserController access a function in db.js. In my UserController, I have included var db = require('../config/db'); and within ...

Effective methods for synchronizing two dropdown menus with varied displays using React

Having a list of countries with specific key-value pairs, I am interested in creating two Dropdown lists. The first will display the keys, while the second will show the corresponding text values. The main objective is to provide the option to select eith ...

The TypeScript error states that the argument type 'string | undefined' cannot be assigned to the parameter type 'string'

Receiving TS error that says "Object is undefined" I am attempting to retrieve the "userid" from my headers. However, I keep encountering the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'str ...

Is there a way to deactivate other dropdown options?

To simplify the selection process, I would like to disable the options for "Province", "City", and "Barangay". When the user clicks on the "Region" field, the corresponding "Province" options should be enabled. Then, when a specific province is selected, t ...

I am encountering some difficulties with the functionality of the angularjs dialog

I've been attempting to integrate an AngularJS dialog feature into my application by following the examples provided on material.angularjs.org. However, despite copying everything accurately, I am unable to get it to function. Can anyone help identify ...

Facing Hurdles in Starting my Debut Titanium Mobile Project

I recently started using Titanium Studio (version 2.1.0GA on WindowsXP) and I have added the Android SDK to it. However, I am encountering an error when trying to run my first mobile project. The console is displaying the following message: Can anyone off ...

Tips for deleting an image file, or any file, from a Node.js Express server

Being a novice in the field of web development, I decided to embark on creating a basic E-commerce application as my first project. I managed to make good progress until I hit a roadblock while trying to remove an image file of a product: I utilized expres ...

Can webpack integrate React components from a package and then recompile the package?

I am currently in the process of creating an npm package to standardize my layout components that are based on geist components. Initially, I attempted to use the npm package as a local component, but encountered a webpack loader error when trying to read ...

Adjusting the value of 'let' based on the outcome

Can you assist me with this issue? I am attempting to assign a value to a let variable based on the following if conditional block. class Main extends React.Component{ render(){ let content = ''; firebase.auth().onAuthStateChanged(func ...

Tips on crafting tailored CSS styling for targeted div elements such as before and after:

Looking to style specific div elements with the same class name? <div class="main"> <div class="banner_image"> banner 1</div> <div class="banner_image ">banner 2</div> <div class="banner_image ">banner 3</di ...

Add JSON elements to an array

Looking for help! {"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]} Need to add these items to a jQuery array. I've attempted using JSON.parse without success. Typically, I can push parameters as follows: MyArr.push([& ...

Looking for assistance with navigating through this URL using Python (requests, beautifulsoup, or selenium) or Javascript (node js, puppeteer)?

While attempting to gather data, I encountered an interesting pagination challenge on the following URL: My expertise in Web Scraping was put to the test as this website implemented a unique JavaScript-driven pagination. For the initial 5 pages, it simply ...

What is the best way to show real-time values using chart js?

Just recently, I've delved into the world of web development and am eager to learn how to integrate chart js for real-time value display. Could anyone offer advice or guide me through the process? var data = []; var temp = []; async f ...

Exploring Ngu-Carousel in Angular 7: Importing JSON data for a dynamic display

After attempting to import data from JSON and display it using ngu-carousel, I encountered an error. The error shows "length of undefined" Subsequently, when I try to click on the previous/next button, another error appears. This error states "innerHTML ...

Access cookie information within a Vue application by reading it within the router or component

There is a url (*/webapp/callback) in my vue.js app that gets redirected (http 302) from another application, bringing along some cookies. I'm trying to figure out how I can read these cookies when the component mounts and then store them in vuex stat ...

The loading of the module from was hindered due to an invalid MIME type restriction

Exploring a three.js example and encountering an issue when utilizing import within a JavaScript module. The error message displayed is: Loading module from “http://localhost:8000/build/three.module.js” was blocked because of a disallowed MIME type ( ...

The response from a Fetch API POST request comes back as a blank text

When I use fetch() to send a post request, the response is coming back empty. Here is my code: JS: async getTotalCompletionTimes() { var res = await fetch("repository/maps.php?method=getcompletiontimes&map="+this.getName(), {method: 'POST&ap ...

Loop through each div using jQuery and dynamically add or remove a class to

I am looking to create an infinite loop that adds a class to each div with a timeout in between. Currently, I have implemented it like this: $(document).ready(function() { $('.small-bordered-box').each(function(i) { var $t = $(this); ...