Using a JavaScript for loop to apply a function across multiple objects

In the game I'm developing, there are three dice cubes that display random faces when a button is clicked. The images are obtained from a CSS image sprite. Each dice cube is assigned a CSS class based on the random number generated.

function diceroll (){

    var randomnumber = Math.floor(Math.random() * (6 - 1 + 1)) + 1;

        switch (randomnumber) {

        case 1:
            document.getElementById("dice1").setAttribute("class", "face1");
            break;
        case 2:
            document.getElementById("dice1").setAttribute("class", "face2");
            break;
        case 3:
            document.getElementById("dice1").setAttribute("class", "face3");
            break;
        case 4:
            document.getElementById("dice1").setAttribute("class", "face4");
            break;
        case 5:
            document.getElementById("dice1").setAttribute("class", "face5");
            break;
        case 6:
            document.getElementById("dice1").setAttribute("class", "face6");
            break;
    }
}

There is a separate button that, when clicked, should execute the 'diceroll' function for three divs with ids dice1, dice2, and dice3.

I would like to implement

function gotoloop (){

    for (i = 0; i < 2; i++) {
        // code that modifies dice(n) where n=1 initially and then calls diceroll function
        // modifying dice1 to dice2 in the next iteration
    }

}

After searching, I couldn't find a way to write the code for the last two commented lines. Please review my approach and provide guidance on how to proceed with the code implementation.

Answer №1

It seems like you are looking for a solution similar to this:

function rollDice (diceId){

    var randomNumber = Math.floor(Math.random() * 6) + 1;

    switch (randomNumber) {

        case 1: document.getElementById(diceId).setAttribute("class", "face1"); break;
        case 2: document.getElementById(diceId).setAttribute("class", "face2"); break;
        case 3: document.getElementById(diceId).setAttribute("class", "face3"); break;
        case 4: document.getElementById(diceId).setAttribute("class", "face4"); break;
        case 5: document.getElementById(diceId).setAttribute("class", "face5"); break;
        case 6: document.getElementById(diceId).setAttribute("class", "face6"); break;
    }
}

function rollLoop (){
    for (var i = 1; i <= 3; i++) {
        rollDice("dice" + i);
    }
}

Alternatively, based on Marc Baumbach's suggestion, you could simplify it like this:

function rollDice (diceId){

    var randomNumber = Math.floor(Math.random() * 6) + 1;

    document.getElementById(diceId).setAttribute("class", "face" + randomNumber);
}

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

Exploring the possibilities of integrating jQuery into Firefox extensions

Can someone provide guidance on effectively implementing jQuery within a Firefox extension? My research has not yielded any up-to-date methods that address the latest version of jQuery, and I am aware that directly including it via script tag may lead to c ...

Save the ID values for dialogs that are created dynamically in the store

Encountering an issue with storing values in dynamically created buttons that can open a dialog box. The dialog is the same for all buttons, so the definition looks like this: $('<div id="dialog-form" title="Change coordinates">' + ...

Solving the enigma of CSS positioning: mastering floats, margin-left/right, and auto

Hey there, I'm having trouble posting an image but here is the link: I believe this explanation will be clearer, D2, D3 & D4 need to be aligned next to each other and centered on the screen at all times. (960px)      & ...

Animating Brightness and Contrast in CSS

I come from a strong background and I am looking to create a dynamic loop that changes the brightness using CSS specifically on Chrome. The goal is to have the background color match the user's profile, providing a unique experience each time. For ex ...

What is the best way to create a loop for this in R?

Organizing my data is proving to be quite a task. I imported a CSV file that contains results from 15 precincts within a single locality. With 10 candidates competing in each precinct, the total number of rows in the file is 150, as each candidate's n ...

Python script that extracts data by checking a box

I am currently attempting to extract links from a job website dedicated to various retail positions. The challenge I'm facing is that in order to scrape the links, I first need to specify a specific brand (such as Sierra). My question revolves around ...

How can I send styles to a child component and utilize them as scoped styles within Vue?

One of my components is a parent: <template> <ChildComponent :styles="styles" /> </template> <script> export default { data: () => ({ styles: ` p { color: red } ` ...

display html once the component is finished rendering in Angular 2

After making an API call in my app component and receiving a response, I need to determine which div to display and which one to hide. However, the HTML is rendered before the component process is complete. Here is an example of the code: user.service.ts ...

Issue with displaying fonts from @font-face on 000webhost

I recently set up my own website. Originally, I was using webs.com as my hosting provider, but they started adding an ad bar to their html-only hosting which I didn't like. So, I switched over to 000webhost. However, after moving everything to 000webh ...

Incorporating the Acts_as_votable gem alongside Angularjs for interactive voting functionality

I'm trying to figure out how to implement Acts_as_Votable in an Angular template for a car voting system. Despite my efforts, I can't seem to display the vote count when rendering the list in Angular. I think I may need to establish some kind of ...

New replacement for routerState.parent feature that has been deprecated in angular2

During my work with Angular 2 rc5, I encountered the following code snippet. this.router.routerState.parent(this.route).params.forEach((params: Params) => { url = params['url']; id = +params['id']; }); I had to resort to th ...

Developing a React project that is steadily progressing

My React apps are taking an unusually long time to build when I use the "npm run build" command in the terminal. It's been over 15 minutes each time. Can anyone provide any insight into what might be causing this delay? ...

Tips for displaying user-entered information from a form after submitting it with PHP

How can I display the email in the email text input field with this code? It doesn't seem to work correctly when there is a failed login attempt. value= "if(isset($_POST['submit'])){ ?PHP echo $_POST[''email']?>"; ...

Strategies for Passing Select ID Using JavaScript/jQuery

Currently, I am working on resolving a problem that is detailed in my post here jQuery/js separating 2 drop down values. I am wondering how to properly pass #dropdown1 in the following code: <select id="dropdown1" multiple="multiple" class="multiselect ...

How can I send an HTML document from a WebApi 2 action using the IHttpActionResult interface?

When it comes to building an html document and returning it in a web api, many resources recommend using HttpResponseMessage. However, I am eager to achieve this using IHttpActionResult instead. Here is my current approach: [ResponseType(typeof(HttpRe ...

Specialized function to identify modifications in data attribute value

I have a container with a form inside, featuring a custom data attribute named data-av Here is how I am adding the container dynamically: > $("#desti_div").append("<div class='tmar"+count+"'><div > class='form-group col-md-6 ...

Having difficulty with submitting a modal form via Ajax Request in Laravel

Attempting to delete a user based on input from a modal form, but encountering difficulty. No error message is showing in the console. As a beginner, struggling to pinpoint the mistake. Error: Ajax request issue. Code snippet below: Blade modal section: ...

Traverse through the div elements with identical class using jQuery

Hey there! I have a bunch of classes named itemdata and I'm looking to incorporate some jQuery within each div. Within every div, there is a link that I want to extract the href attribute value from and enclose it within another <span> in that s ...

Utilizing async/await functionality within a React-Native component

I'm currently working on implementing a feature that authenticates users before rendering the main 'App' component. However, I'm facing an issue where my code is executing before the promise is resolved. class App extends Component { ...

Step-by-step guide on creating a login functionality in Node using the Mean.io stack

I'm currently working on a web app using the MEAN.io stack. I have completed the frontend part with HTML, CSS, and AngularJS along with some logic. Now, I am looking to implement server-side login functionality, but I'm unsure where to begin sinc ...