What is the best way to apply changes to every class in JavaScript?

Check out this HTML and CSS code sample!

body{
  font-family: Verdana, Geneva, sans-serif;
}

.box{
  width: 140px;
  height: 140px;
  background-color: red;
  display: none;
  position:relative;
  margin-left: auto;
  margin-right: auto;
}

.bold{
  font-weight: bold;
}
.table{
  border: 2px solid black;
  height: 150px;
  width: 150px;
}




</style>

<p class="bold">Your Time: <span id="time">0.000</span>s</p>

<table id="table">
  <tbody>
    <tr>
      <td class="table"><div class="box"></div></td>
      <td class="table"><div class="box"></div></td>
      <td class="table"><div class="box"></div></td>
    </tr>
    <tr>
      <td class="table"><div class="box"></div></td>
      <td class="table"><div class="box"></div></td>
      <td class="table"><div class="box"></div></td>
    </tr>
    <tr>
      <td class="table"><div class="box"></div></td>
      <td class="table"><div class="box"></div></td>
      <td class="table"><div class="box"></div></td>
    </tr>
  </tbody>
</table>

<script type="text/javascript">


function getRandomColor() {
     var letters = '0123456789ABCDEF'.split('');
     var color = '#';
     for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
 }


var clickedTime; var createdTime; var reactionTime;


function makeBox(){

    createdTime=Date.now();

    var time = Math.random();

    time = 5000*time;

    var box = document.getElementsByClassName("box");

    setTimeout(function(){

      if(Math.random()>0.5){


        for (var i=0;i<box.length; i++) {
              box[i].style.borderRadius="100px";

        }else{

          for (var i=0;i<box.length; i++) {
            box[i].style.borderRadius="0";
          }

        for (var i=0;i<box.length; i++) {
            box[i].style.backgroundColor=getRandomColor();
          }

        for (var i=0;i<box.length; i++) {
            box[i].style.display="block";
          }
          
        createdTime=Date.now();
    }, time);
}

       for (var i=0;i<box.length; i++) {
            box[i].onclick=function(){

        clickedTime=Date.now();

        reactionTime=(clickedTime-createdTime)/1000;

        document.getElementById('time')[0].innerHTML=reactionTime;

        this.style.display="none";

        makeBox();
   }

   makeBox();

</script>

I am working on a project to show various shapes in 9 boxes simultaneously but only one shape at a time appears when I run this code. I have tried accessing elements by class and using loops, but it doesn't seem to work as intended. Any suggestions or alternatives would be greatly appreciated!

Answer №1

Did you customize the box class with any CSS styles? If not, the dimensions might be set to 0, resulting in nothing being visible.

To fix this, consider adding the following code snippet inside the <head> section of your HTML file:

<style>
.box
{
    width:150px;
    height:150px;
}
</style>

Answer №2

Everything seems to be running smoothly with your script,

Just don't forget to assign a width and height to your .box elements:

Check out the live demo on JSFiddle: http://jsfiddle.net/FloSchieldBobby/1gb0ae9q/

var box = document.getElementsByClassName("box");

var getRandomColor = function () {
    return 'rgb(' + Math.floor(Math.random() * 255) + ', ' + Math.floor(Math.random() * 255) + ', ' + Math.floor(Math.random() * 255) + ')';
};

setTimeout(function(){
    
    if (Math.random() > 0.5) {
        
        for (var i=0;i<box.length; i++) {
            box[i].style.borderRadius="100px";
        }
        
    } else {
        for (var i=0;i<box.length; i++) {
            box[i].style.borderRadius="0";
        }
    }
    
    for (var i=0;i<box.length; i++) {
        box[i].style.backgroundColor=getRandomColor();
        box[i].style.display="block";
    }
    
    createdTime = Date.now();
}, 100);
#table {
    width: 100%;
}

#table .box {
    width: 50px;
    height: 50px;
}
<table id="table">
    <tbody>
        <tr>
            <td class="table"><div class="box"></div></td>
            <td class="table"><div class="box"></div></td>
            <td class="table"><div class="box"></div></td>
        </tr>
        <tr>
            <td class="table"><div class="box"></div></td>
            <td class="table"><div class="box"></div></td>
            <td class="table"><div class="box"></div></td>
        </tr>
        <tr>
            <td class="table"><div class="box"></div></td>
            <td class="table"><div class="box"></div></td>
            <td class="table"><div class="box"></div></td>
        </tr>
    </tbody>
</table>

#table {
    width: 100%;
}

#table .box {
    width: 50px;
    height: 50px;
}

Answer №3

It seems like there may be some confusion between setTimeout and setInterval. If you want to understand the difference, take a look at this link.

  var box = document.getElementsByClassName("box");

 function getRandomColor() {
     var letters = '0123456789ABCDEF'.split('');
     var color = '#';
     for (var i = 0; i < 6; i++) {
         color += letters[Math.floor(Math.random() * 16)];
     }
     return color;
 }

 setInterval(function () {
     console.log("Tick");
     if (Math.random() > 0.5) {

         for (var i = 0; i < box.length; i++) {
             box[i].style.borderRadius = "100px";
         }

     } else {

         for (var i = 0; i < box.length; i++) {
             box[i].style.borderRadius = "0";
         }

         for (var i = 0; i < box.length; i++) {
             box[i].style.backgroundColor = getRandomColor();
         }

         for (var i = 0; i < box.length; i++) {
             box[i].style.display = "block";
         }


     }
 }, 1000);

Answer №4

There were a few syntax errors in the code snippet, such as missing closing curly brackets }:

var box = document.getElementsByClassName("box");

setTimeout(function() {

  if (Math.random() > 0.5) {

    for (var i = 0; i < box.length; i++) {
      box[i].style.borderRadius = "100px";
    }

  } else {

    for (var i = 0; i < box.length; i++) {
      box[i].style.borderRadius = "0";
    }

    for (var i = 0; i < box.length; i++) {
      box[i].style.backgroundColor = 'orange'; // replaced with `getRandomColor()` for testing
    } 
    for (var i = 0; i < box.length; i++) {
      box[i].style.display = "block";
    } 
    createdTime = Date.now();
  } 
}, 100); // replaced with `time` for testing
.box {
  border: 1px solid grey;
  padding: 3px 4px;
  width: 50px;
  height: 50px;
  background: skyblue;
}
<table id="table">
  <tbody>
    <tr>
      <td class="table">
        <div class="box"></div>
      </td>
      <td class="table">
        <div class="box"></div>
      </td>
      <td class="table">
        <div class="box"></div>
      </td>
    </tr>
    <tr>
      <td class="table">
        <div class="box"></div>
      </td>
      <td class="table">
        <div class="box"></div>
      </td>
      <td class="table">
        <div class="box"></div>
      </td>
    </tr>
    <tr>
      <td class="table">
        <div class="box"></div>
      </td>
      <td class="table">
        <div class="box"></div>
      </td>
      <td class="table">
        <div class="box"></div>
      </td>
    </tr>

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

displaying a Google Map within a designated container

I'm currently working on a basic website layout that consists of a full-width banner, a left menu (200px), and right content (600px). I have a simple jQuery script set up to load the content on the right-hand side when any of the five menu items are c ...

Javascript alert: An issue has been detected when attempting to open a URL along with the user's input through Javascript

Having trouble with my javascript codes... I'm trying to create an input box and submit button. Whatever the user inputs in the box should be added to the default web URL, but it's not functioning as expected. The issue I'm facing is that ...

Accessing an array of objects within nested objects results in an undefined value

I am facing an issue with my JavaScript object that is retrieved from MySQL. The object has a property which contains an array of other objects, as demonstrated below: parentObject = { ID: "1", Desc: "A description", chi ...

Fixing the issue of a div exceeding the height of its parent div in Tailwindcss

One issue I'm encountering is with my card element, which has a fixed height of h-80 in Tailwind. Typically, I use this card within a grid. However, I recently added a div inside the card that is larger than its parent div, and I want it to scroll ve ...

making changes to the JS node dependency package results in a syntax error during compilation process, particularly within the npm/Vue.js environment

After creating a Js library and encountering stability issues and a few bugs that need fixing, the dilemma of developing a library arises when HMR does not work with dependencies. Here's a possible solution: To start, create a new Vue project using ...

Vue composable yields a string value

I am currently using a Vue composable method that looks like this: import { ref } from 'vue'; const useCalculator = (num1: number, num2: number, operation: string) => { const result = ref(0); switch (operation) { case 'add& ...

The delete function is not functioning

I need help with implementing a custom Angular directive that includes a delete button to remove itself. When I click the button removeMe, it is not deleting an item from the array. Any suggestions on what might be causing this issue? HTML: <button t ...

Is there a way to store a JSON object retrieved from a promise object into a global variable?

var mongoose = require('mongoose'); var Schema = mongoose.Schema; const NewsAPI = require('newsapi'); const { response } = require('express'); const newsapi = new NewsAPI('87ca7d4d4f92458a8d8e1a5dcee3f590'); var cu ...

Remove the initial 15,000 lines from a text file using Node.js

Looking for a way to delete the first 15,000 lines of a large text log file (roughly 20MB) using Node.js. Any suggestions on how to accomplish this task? ...

Execute a jQuery ajax request to a specific variable

For my Phonegap/Cordova project, I have implemented functions to handle all ajax calls in the following way: function requestData(action, id ) { var data = { user_id: localStorage.getItem('user_id') }; if( action == 'fee ...

Struggling with uploading files in AngularJS?

Below is the code snippet from my controller file where I aim to retrieve the values of various input elements (name, price, date, image) and store them in an array of objects... $scope.addBook = function(name, price, date, image) { name = $scope ...

Exploring jQuery: Moving between different table cells using traversal techniques

Seeking assistance from experienced jQuery users as I am new to this library and may not be approaching this task correctly. I have a dynamically generated HTML table that is quite extensive. To enhance user experience, I aim to assign navigation function ...

How can I write this to function on click events?

Could someone please help me with a simple question I have? I am struggling to properly write the code. $wish_1='<span onclick=alert("Register or Login Now");></span>'; The issue is that spaces are not working and using ' also ...

What is the process of overriding methods in a function-based component in React?

Overriding in a parent component works when it is a class-based component // Parent Button Class class Button extends React.Component { createLabel = () => { return <span>{this.props.label}</span>; }; render() { return <butt ...

What design pattern serves as the foundation for Angularjs? Is mastering just one design pattern sufficient?

Although I have been teaching myself Angular and can understand how to code in it, I realize that simply learning the concepts of AngularJS and coding or tweaking things to solve problems is not enough. Moving forward, my goal is to write effective and sta ...

Is there a way to establish communication between two ReactJS components by utilizing Jotai?

I am facing a problem with 2 reactjs files: Reports.js (handles report requests and displays results) AuthContext.js (maintains communication with backend server through a socket connection) The user initially visits the report page generated by Reports. ...

AWS Lambda Error: Module not found - please check the file path '/var/task/index'

Node.js Alexa Task Problem Presently, I am working on creating a Node.js Alexa Skill using AWS Lambda. One of the functions I am struggling with involves fetching data from the OpenWeather API and storing it in a variable named weather. Below is the relev ...

Is it possible to pass the index variable of a for loop to a different function?

As a current bootcamp student, I have a question about passing the index of a for loop to another function. Specifically, I am trying to fetch data from an API (which provides me with a random cryptocurrency from an array) 4 times and then pass that data ...

How come I am unable to reach the window in my Next.js application's '_app.js' file?

In my Next.js application, I am trying to implement a feature where the app loads and then checks for network access using a custom modal dialog that alerts the user if they lose internet connection. I have set up an _app.js file in my application to estab ...

The onchange function seems to be malfunctioning when attempted with AJAX

Help needed: I'm new to AJAX and facing an issue. I have implemented AJAX pagination to display data, which is working fine. But now I want to add a filter to the displayed data, however, the filter is not functioning correctly. <select name="prof ...