Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

198
Views
Set <div> background color on load, then change between 3 colors when clicked

I am trying to set the background color of a div upon page load to blue. Then I want to cycle through 3 different colors (red, yellow, and green) when clicked and have the selected color remain. Below is my sample code. You can see the first two do nothing when clicked due to setting the blue color on load. I didn't load the 3rd div to blue on load to show how I want the behavior to act once clicked. Any help is appreciated.

    function colorload() {
    
        var element = document.getElementById("day1");
        element.style.backgroundColor = "blue";    
    
        var element = document.getElementById("day2");
        element.style.backgroundColor = "blue";    
     
    }
    
    function changeColor(e, numb) {
        var color = e.className;
        e.className = (color == 'red') ? 'amber' : 
                      (color == 'amber') ? 'green' : 
                      (color == 'green') ? 'red' : 
                      'undefined'; 
    
    }
    <style onload="colorload()">
    .red {background-color:red;}
    .amber {background-color:yellow;}
    .green {background-color:green;}
    
    
    div {
        width:200px;
        height:100px;
        margin:50px;
        text-align: center;
        vertical-align: middle;
        line-height: 90px;
        font-weight:bold;
        user-select: none;
        cursor:pointer;
        }
</style>
  
    
    <html>
        <body>
            <div class="red" id="day1" onclick="changeColor(this, 1)">One</div>
            <div class="green" id="day2" onclick="changeColor(this, 2)">Two</div>
            <div class="amber" id="day3" onclick="changeColor(this, 3)">Three</div>
        </body>    
    </html>
    
    
   

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

i made an update to your html and JS codes, i used in this example .style instead of css classes, if you are interested on using classes you can refer to my comments and this link on mdn it's pretty simple.

Html file

<html>
    <body>
        <!-- i used .btn class and data-col to play with indexes -->
        <div class="btn" id="day1" data-col="0" onclick="changeColor(event)">One</div>
        <div class="btn" id="day2" data-col="0" onclick="changeColor(event)">Two</div>
        <div class="btn" id="day3" data-col="0" onclick="changeColor(event)">Three</div>
    </body>    
</html>

Js file

let divs;
let colors = ['blue', 'red', 'green' , 'yellow'];

// when loading the page, we are catching all divs having the class "btn"
// to render it with Blue background
document.body.onload = function() {
    divs = document.querySelectorAll('.btn');
    divs.forEach(btn => {
       const selectedColorIndex = btn.dataset.col;
       btn.style = 'background:'+colors[selectedColorIndex];
    });
};


function changeColor(e) {
    // catch the clicked div which passed by the "event" value in the html file
    let divElement = e.target;

    // get data-col value and convert it to number with (+)
    const selectedColorIndex = +divElement.dataset.col;

    // check if we have a next color or get the red index
    const nextSelectedColor =  selectedColorIndex +1 >= colors.length?1:selectedColorIndex+1;

    // update data-col with the next new color index to conserve the iteration (loop)
    divElement.dataset.col = nextSelectedColor;

  // if you want to use classes you can access with 
  // .classList.add(..) and .classList.remove(..) OR 
  // .classList.toggle(..)
    divElement.style = 'background:'+ colors[nextSelectedColor]; // update the element background with selected color
}

You can also replay the same codes or update: it here is the full replayed code in JSFiddle which i made to make it more easy.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!