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

Changing Highcharts Donut Chart Title Text via Legend Item Click in React

Utilizing React. In my Highcharts donut chart, there are 5 legend items of type 'number' and a 'title text' (also type: number) displayed at the center. The title text represents the sum of all the legend items. However, when I click o ...

The error message from the mongoose plugin is indicating a problem: it seems that the Schema for the model "Appointment" has not been properly registered

I need help troubleshooting a mongoose error that is being thrown. throw new mongoose.Error.MissingSchemaError(name); ^ MissingSchemaError: Schema hasn't been registered for model "Appointment". Use mongoose.model(name, schema) I have double-c ...

"Transforming a static navbar to a fixed position causes the page to jump

Having some difficulty figuring this out. I'm working on a bootstrap navbar that transitions from static to fixed when the user scrolls past the logo at the top. Everything seems to be working fine, except for when the navbar reaches the top, it sudde ...

Guide to adding up the radio button values with Javascript

The tutorials I have reviewed include: How might I calculate the sum of radio button values using jQuery? How to find a total sum of radio button values using jQuery/JavaScript? How might I calculate the sum of radio button values using jQuery? Unfortu ...

Unable to load files in Handlebars when using Node and Express

Currently, I am in the process of developing a Node/Express web application for basic CRUD operations. However, I am encountering difficulties incorporating Handlebars into my project. Whenever I attempt to utilize Handlebars, none of the stylesheets from ...

Update the page when the React route changes

I am facing an issue with a function in a component that is supposed to load certain variables when the page is fully loaded. Interestingly, it works perfectly fine when manually reloading the page. However, if I use a NavLink to navigate to the page, the ...

Find the nearest minute when calculating the difference between two dates

To determine the difference between dates and round to the nearest minute, you can choose to either round date1 or date2 up or down. The result returned is already rounded up to the full minute. You have the flexibility to modify date1 and date2, but do no ...

Dealing with TypeScript and the Mongoose loadClass problem

Working with Mongoose's class schemas has been very beneficial for me. Incorporating TypeScript into my Node project has enhanced the development process. I made sure to refer to Mongoose the Typescript way...? in order to ensure that my Model align ...

Deliver a communication from the dialogue box on the MEAN stack website to the task pane

Currently experimenting with the Dialog API within Office addins. Able to successfully trigger a Dialog box from my task pane using: $scope.openDialog = function () { Office.context.ui.displayDialogAsync('https://localhost:3000/home', ...

Generating directives on the fly

I am relatively new to AngularJS and have a good understanding of the basics. My goal is to create a desktop interface where items are loaded dynamically from a database using $http. I have already developed a directive that displays a title and an icon fo ...

unusual behavior observed in addEventListener

I have recently delved into learning about the DOM. I have a project in mind where I want to create a website with buttons that, when clicked, play different drum sounds. As part of my experimentation with JavaScript, I wanted to explore the this keyword. ...

Adjust alterations in a Vue Component to apply to separate routes

I have a Filter tab component that I use in various routes. When I click on a tab, it becomes active. After clicking on one tab, I want it to remain active in other routes as well. How can I achieve this? Any suggestions or articles would be greatly apprec ...

What methods are available to generate dynamic shapes using HTML?

Looking to create an interactive triangle where users can move vertices or sides, updating angles in real-time. I'm struggling with how to accomplish this task. My initial attempt was to manually draw the triangle using the code below. <!DOCTYPE ht ...

The error message received is: "mongoose TypeError: Schema is not defined as

Encountering a curious issue here. I have multiple mongoose models, and oddly enough, only one of them is throwing this error: TypeError: Schema is not a constructor This situation strikes me as quite odd because all my other schemas are functioning prop ...

React does not recognize data.map as a function

Currently, I am facing an issue with a simple map function in React that is supposed to create a set amount of times. {times.map((time) => ( <Pill value={time} handleTimes={handleTimes} key={time} /> ))} The error being thrown i ...

Apply CSS styling (or class) to each element of a React array of objects within a Component

One issue I'm facing involves adding specific properties to every object in an array based on another value within that same object. One such property is the background color. To illustrate, consider an array of objects: let myObj = { name: "myO ...

The automated Login Pop Up button appears on its own and does not immediately redirect to the login form

Hey guys, I'm struggling with modifying the jquery and html to ensure that when the login button is clicked, the login form pops up instead of displaying another login button. Another issue I am facing is that the login button seems to pop up automati ...

Utilize CSS to vertically align buttons

One of my current projects involves creating a panel with buttons organized in columns side by side, similar to the layout shown below: However, I am struggling to achieve this desired arrangement. Below is the code I have been working on: <style&g ...

Nextjs: where all roads lead back to the homepage

Having an issue in my app where all redirects keep leading back to the homepage. The problem seems to stem from my Navbar.js component, as shown below. Despite adding the required route in the Link tag for next-js, both client and server compilation is suc ...

Enhancing the efficiency of typed containers in JavaScript

Recently, I uncovered a clever method for creating fake 'classes' in JavaScript, but now I'm curious about how to efficiently store them and easily access their functions within an IDE. Here is an example: function Map(){ this.width = 0 ...