Can you make two elements match each other at random?

Currently, I am working on developing a word guessing game where the displayed image should correspond with the word to be guessed. Unfortunately, I am encountering two major challenges in this process. Firstly, I am unable to get the image to display correctly. Secondly, even when the image does display, it does not align accurately with the word to be guessed.

Answer №1

"Is there a way to ensure that the displayed image matches the word being guessed? Why use random indexes for imgPaths?

I propose storing imgPaths as key-value pairs.

let newGame = function () {
  let wordsArray = [
    "basketball",
    "soccer",
    "baseball",
    "hockey",
    "cricket",
    "swimming",
    "golf",
    "chess",
    "badminton",
    "skiing",
    "volleyball",
  ];

  let imgPaths = {
    "badminton": "Images/badminton.png",
    "baseball": "Images/baseball.png",
    "basketball": "Images/basketball.png",
    ...
  };

  //select random word from wordArray
  let selectedWords = wordsArray[Math.floor(Math.random() * wordsArray.length)];
  let selectImg = imgPaths[selectedWords];
  document.getElementById("gamePic".src) == selectImg;

Answer №2

I think using an array of objects containing both words and images would make the matching process simpler. Below is an example with a corrected method for changing the image source and an additional div for debugging purposes to display the selected image source.

const newGame = function () {
    const answersArray = [
    {
      word: "football",
      img: "Images/football.png"
    },
    {
      word: "baseball",
      img: "Images/baseball.png"
    },
    {
      word: "tennis",
      img: "Images/tennis.png"
    },
    {
      word: "hockey",
      img: "Images/hockey.png"
    },
    {
      word: "swimming",
      img: "Images/swimming.png"
    }
  ];

  //select random word from wordArray
  const selectedAnswer = answersArray[Math.floor(Math.random() * answersArray.length)];
  document.getElementById("gamePic").setAttribute("src", selectedAnswer.img);
  document.getElementById("gamePicSrc").innerHTML = selectedAnswer.img;
  document.getElementById("gameWord").innerHTML = selectedAnswer.word;
 }
 
 newGame();
<div id="gameDiv">
  <img id="gamePic" src="Images/placeholder.png">
  <div id="gamePicSrc">
  
  </div>
  <div id="gameWord">

  </div>
</div>

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

Tips for assigning unique non-changing keys to siblings in React components

I've been searching for a solution for more than an hour without success. The structure of the data is as follows: const arr = [ { id: 1, title: 'something', tags: ['first', 'second', 'third'] }, { id: 2, t ...

The response from NodeJS is not being properly parsed by Express or BodyParser

const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const adminRoutes = require('./routes/admin'); const shopRoutes = require('./routes/shop'); // app.use(express.u ...

Experiencing difficulties when utilizing Jest to test components

I recently started working with Jest and JavaScript. I wrote a test for one of my components, but it's failing, and I'm struggling to figure out what's wrong (seems like something related to enzyme). Here is the output: ● Console co ...

JavaScript code that iterates through all files in a designated folder and its subfolders using a for loop

I am looking to combine two JavaScript scripts into one, but I'm not sure how to do it. The first script uploads files from a specified folder to VirusTotal for scanning and returns the scan result. The second script lists all files in the specified ...

Choose the list item below

I'm working on a website that includes a select list with images. Here's what I have so far: When I choose an image from the list, it should display below. <?php // Establish database connection $con=mysqli_connect("******","***","*** ...

What is the method for sending raw put data using the request npm package in a Node.js environment

How can I hit an API using the "require" npm package in Node? The API requires raw PUT data instead of PUT fields. Can anyone please guide me on how to achieve this using the request npm package? For example, here is the raw PUT data that needs to be sent ...

Exploring the world of third-party widgets: Comparing Angular, jQuery, and traditional JavaScript

I have a plan to develop a simple embeddable widget similar to Google ads or Facebook like box. Users will be able to easily add the widget to their website and I will extract some parameters to fetch data from my servers. Previously, I relied on jQuery f ...

React-easy-crop simply provides a blob url as a result

Currently, I am utilizing the react-easy-crop package to enable users to make adjustments to their profile pictures post uploading. However, I have encountered an issue where the cropped image is returned in the form of a blob URL such as blob:http://local ...

What is the process for creating a custom Vue 3 element with incorporating styles for child components?

After experimenting with Vue's defineCustomElement() to develop a custom element, I encountered an issue where the child component styles were not being included in the shadow root for some unknown reason. To address this problem, I took a different ...

Is incorporating RequireJS into an AngularJS project a valuable decision?

Is it true that AngularJS has its own module loading mechanism built-in and using RequireJS is unnecessary or even inefficient? I am working on an Angular project where the index.html file is becoming quite large. Would incorporating RequireJS help reduc ...

I want to set a single background image for all slides in fullPage.js. How can I achieve this

I am attempting to replicate a similar effect as shown in this example: The demonstration above utilizes the fullPage.js plugin. You may have noticed how the background image remains consistent while navigating through different sections. I have searched ...

Executing a function when a webpage loads in Javascript

I have created a responsive website using Twitter Bootstrap. On my site, I have a video displayed in a modal that automatically plays when a button is clicked. Instead of triggering the function with a button click, I want the function to be called when ...

What is the best way to implement a timer or interval system in React and Next.js that continues running even when the tab is not in focus or the browser is in

I am attempting to create a stopwatch feature using next js. However, I have encountered an unusual issue where the stopwatch does not function correctly when the tab is not focused or when the system goes to sleep or becomes inactive. It appears that the ...

Transforming a set of properties into an organized array

Looking to transform an object literal that contains inner objects with a "rank" key holding floating point values into an array of these inner objects, sorted by the "rank" value. Input Object: { 452:{ bla:123, dff:233, rank:2 }, 234:{ ...

How can I eliminate the default background of Mui tooltip and personalize it in react?

Below is an example of how to customize a nested tooltip within a default background tooltip in MUI. The challenge here is to remove the grey border in the customized tooltip and have only a white background with black text. Check out the code snippet be ...

Issues related to validation prior to submission

Having trouble with a VeeValidate example from the documentation. The example can be found here. I seem to be missing something crucial but can't figure out what it is. For some reason, my form always validates as valid, even when no text is entered ...

Is there a way to create a new prettyphoto window by clicking on a link within the original prettyphoto window?

I have an HTML table that is dynamically constructed on the server side using AJAX. The table is displayed using prettyphoto, everything works fine up to this point. However, the last column of the table contains a link that should open an image using pret ...

Is it possible to upload files without using AJAX and instead through synchronous drag-and-drop functionality in the foreground?

Currently, my website has a standard <input type="file"> file upload feature that sends data to the backend upon form submission. I am looking to enhance the functionality of the form by allowing users to drag and drop files from anywhere within the ...

The form data is being passed as null to HttpContext.Current.Request

My file upload module is working well with Postman without any content type. However, in the code, the file count always shows as 0 in the backend API. If anyone has any insights into what I might be doing wrong, please help me out. Thank you. Below is my ...

NodeJS and ExpressJS fail to redirect to the main landing page

I am currently developing a shopping cart application using nodejs/expressjs. I have encountered an issue with redirecting back to the homepage ('/') after the user submits their credentials during sign up. Despite my search for relevant articles ...