Using a Javascript function to randomly switch the image displayed on an HTML document

Seeking guidance for completing a homework assignment, I want to clarify that I am not asking for answers to be provided. Rather, I simply need some direction.

The task at hand is creating a dice game. My main challenge lies in connecting Javascript code with the dice images in the HTML file.

For instance:

If running this code :

var dice1 = Math.round(Math.random() * 6);

Returns a value like 4, I wish for it to display the image dice_4.png corresponding to that result.

Here is the HTML code for the cube/dice:

<div class="wrap">
  <div class="cube">
    <div class="front"></div>
    <div class="back"></div>
    <div class="top"></div>
    <div class="bottom"></div>
    <div class="left"></div>
    <div class="right"> </div>
  </div>
</div>

And the respective CSS styling:

.front {
  background-image: url('Images/dice_1.png');
  background-size:100%;
}
.back {
  background-image: url('Images/dice_6.png');
  background-size:100%;
}
.right {
  background-image: url('Images/dice_4.png');
  background-size:100%;
}
.left {
  background-image: url('Images/dice_3.png');
  background-size:100%;
}
.top {
  background-image: url('Images/dice_2.png');
  background-size:100%;
}
.bottom {
  background-image: url('Images/dice_5.png');
  background-size:100%;
}

A 3D cube design was implemented without rotation effects.

To summarize, when a random value like 4 is generated for the first cube, I intend for the .right portion of the CSS file to be displayed in the HTML.

If my explanation appears confusing, please let me know so I can provide further clarification.

Any suggestions on where to focus my attention for resolving this issue would be greatly appreciated.

(Apologies for any formatting errors, as this is my initial attempt).

Thank you.

Answer №1

If you are required to maintain the exact HTML structure as provided:

<div class="wrap">
  <div class="cube">
    <div class="front"></div>
    <div class="back"></div>
    <div class="top"></div>
    <div class="bottom"></div>
    <div class="left"></div>
    <div class="right"> </div>
  </div>
</div>

Then, you will need a method to link dice numbers with cube side divs. A recommended approach would be to use an array of class names.

var dice1 = Math.round(Math.random() * 5);
var sides = ['front', 'top', 'left', 'right', 'bottom', 'back'];
var cubeSides = document.getElementsByClassName('cube')[0].children;
for (var i = 0; i < cubeSides.length; i++) {
  // If each cube side div only has one associated class.
  cubeSides[i].style.display = cubeSides[i].className === sides[dice1] ? 'block' : 'none';
  // If a side div can have multiple classes, use this statement instead.
  // cubeSides[i].style.display = cubeSides[i].className.split(' ').indexOf(sides[dice1]) > -1 ? 'block' : 'none';
}

View the demo.

However, if you are allowed to modify the HTML structure to arrange the div's in ascending order:

<div class="wrap">
  <div class="cube">
    <div class="front"></div>
    <div class="top"></div>
    <div class="left"></div>
    <div class="right"></div>
    <div class="bottom"></div>
    <div class="back"></div>
  </div>
</div>

The code simplifies by arranging the div elements differently:

var dice1 = Math.round(Math.random() * 5);
var cubeSides = document.getElementsByClassName('cube')[0].children;
for (var i = 0; i < cubeSides.length; i++) {
  cubeSides[i].style.display = i === dice1 ? 'block' : 'none';
}

View the demo.

Answer №2

let randomNumber = Math.floor(Math.random() * 10) + 1;
document.getElementById("result").innerHTML = randomNumber;
let imageUrl = 'url(Images/dice_'+randomNumber +'.jpg)';
document.getElementById('dice').innerHTML = imageUrl;
// applying styles
document.getElementsByClassName('dice')[0].style.backgroundImage=imageUrl;
<p id="result"></p>
<div id="dice"></div>
<div class="dice"></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

What is the best way to adjust the width of a div based on the remaining space in the viewport?

I've created a Wireframe to showcase the concept I'm aiming for. There are 2 screens included to illustrate how the layout should adapt to different screen sizes. Check out the Wireframe here The goal is to have a center-aligned container named ...

Tips for dynamically adding divs inside a parent div until its width and height are fully utilized

Background: At this moment, I am in the process of creating a webpage where users will input tile width & height along with floor width & height. The aim is to calculate the area of the floor, with tiles measured in inches and the floor input measured in f ...

Tips for adding/removing items in arrays using Ember.js

Is it possible to modify an array within an Ember object using methods like push and pop while still keeping the UI bindings updated? While I can easily display the contents of an array in an Ember object using Handlebars, making changes directly to the ...

Steps for adjusting the structure of an array of objects according to the ParentID

I need to reorganize an array of objects based on a field called ParentID. Here is an example dataset: var JsonVal = "data": { "Factorid": 197325, "orders": [ { ...

Exploring ways to customize the selected text color within a jQuery mobile division using CSS

Is there a way to change the color of selected text to #3C3 for the div one only and not for div two? <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link ...

Having difficulty getting AJAX requests or session management to work properly

I have a service that is very similar to the one discussed in this thread: Php: Form auto-fill using $_SESSION variables with multiple php files I wanted to ask my question there, but I don't have enough reputation points. So, I'm posting a new ...

Data loading issue with asp.net mvc Ajax

I am currently facing an issue while attempting to fetch data from the controller using ajax. Controller [HttpGet] public ActionResult GetServices() { var data = _bbdb.ListServices.Where(d => d.Status == true).ToList(); return Json(data, JsonR ...

Encountering an error message about an existing Sequelize index while running my application

I crafted this migration file: 'use strict'; module.exports = { async up(queryInterface, Sequelize) { await queryInterface.createTable('note_tags', { id: { type: Sequelize.INTEGER, allowNull: false, ...

Vue.js is like the modern version of jquery-cron

Is there a similar tool to jquery-cron with an easy-to-use text/select interface that anyone knows of? I've come across vue-cron and point-vue-cron, but they seem too complicated for my needs. ...

Combining arrays of JSON Objects and organizing them with Javascript

I have a JSON object containing arrays for different country regions. I am attempting to combine these arrays into a single select dropdown menu. The JSON structure is as follows: "latinamerica": [ "Argentina", "Bolivia", "Brazil", ...

Angular lacks the ability to directly set HTTP headers, except when using an interceptor

When utilizing an HTTP interceptor to include an authentication token in all requests, I encountered a scenario where I needed to add a different token instead of the standard auth token for a specific request. The challenge I faced was the inability to se ...

- Removing the img tag from an HTML document: A guide

When I use quick watch, this is the innerHtml output: <img style="width: 100%; height: 320px;" src="img/banner03.jpg"> <div class="bjqs-caption"> Automatically generated caption3 </div> However, I want the innerHTML to b ...

Iterating over images and displaying them in Laravel's blade templating engine, updating outdated Angular code

Currently, I am in the process of transitioning an Angular repeat function used for displaying images on our website (built with Laravel). The goal is to eliminate Angular completely and handle everything using Laravel loops in the blade template. I have ...

What is the best way to populate a select input field with options using JavaScript?

When I am loading an HTML table, there is a select input field that needs to display some options. Immediately after constructing the HTML table row, I invoke a function to populate this input field using its class. Below is the relevant HTML snippet and ...

Adding custom styles to an unidentified child element in React using Material-UI

When the function below is executed in a loop, I need to include styles for the icon which will be passed as an argument to the function. The icon element will be an unspecified React Material-UI Icon component. const renderStyledCard = (lightMode, headi ...

Error: webpack is failing to load the style and CSS loaders

I'm currently experimenting with the FullCalendar plugin from fullcalendar.io. They recommended using Webpack as a build system, which is new to me. I managed to set up the calendar functionality after some research, but I'm facing issues with th ...

OrbitControls altering the view of the camera

I'm currently immersed in an academic undertaking involving the use of THREE.js and Blender. Within my main.js file, I've crafted the necessary code to set up a scene, establish a renderer, position a camera, implement orbit controls, and more. H ...

Would you like to learn how to extract data from a specific textbox using jQuery and save it to a variable when the textbox is in

Below is a textbox that I am working on: <input type="text" name="company" id="company" required /> I am trying to figure out how to use jQuery to capture the values inside the textbox whenever they are typed or selected. Despite my efforts, I hav ...

How can you connect a jQuery UI sortable component to an array?

Is there a way to connect a jQuery UI sortable element with an array in order to assign an index to each sortable element within the array? I am looking for a method to automatically sort the array based on the movement of the sortable elements. Any sugg ...

Click to stay in the background

I am currently facing an issue where opening a new tab on click redirects the focus to the child window instead of staying in the current window. I would like the popup to open without blocking and allowing me to maintain focus on my current window. The c ...