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

167
Views
Toggling the color of a div box using JS

I'm trying to change the background color of this div box whenever it gets clicked. For some reason the funtcion only works whenever I click on the same div box twice. Am I missing something?

function selected_platz(platz_id)
{
    if(document.getElementById(platz_id).style.backgroundColor == "rgb(0, 168, 0)")
    {
        document.getElementById(platz_id).style.backgroundColor = "blue";
        return;
    }
    document.getElementById(platz_id).style.backgroundColor = "rgb(0, 168, 0)";
}
<div class='div_platz' onclick='selected_platz(this.id)' id='".$row['platz_id']."'>".$counter."</div>

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

0

element.style refers to inline styles only (styling via the HTML attribute style="background-color: blue;"). Initially, your element doesn't have such an attribute.

Use a selected CSS class instead, and toggle that on click:

.div_platz { background-color: rgb(0, 168, 0); }
.div_platz.selected { background-color: blue; }
<div class='div_platz' onclick='this.classList.toggle("selected")' id='".$row['platz_id']."'>".$counter."</div>

It would be even better if you also didn't use inline event listeners. Instead attach the listener via Javascript:

document.addEventListener('DOMContentLoaded', () => {
  let places = document.querySelectorAll('div.div_platz');
  for (const place of places) {
    place.addEventListener('click', function() {
      place.classList.toggle('selected');
    })
  }
});
.div_platz { background-color: rgb(0, 168, 0); }
.div_platz.selected { background-color: blue; }
<div class='div_platz' id='".$row['platz_id']."'>".$counter."</div>

about 4 years ago · Juan Pablo Isaza Report

0

Simply add the color through CSS and toggle a class with a blue backgroun-color with .classList.togle('class-name')

function selected_platz(platz_id) {
  document.getElementById(platz_id).classList.toggle('bg-blue');
}
div {
  background-color: rgb(0, 168, 0);
}

.bg-blue {
  background-color: blue;
}
<div class='div_platz' onclick='selected_platz(this.id)' id='".$row[' platz_id ']."'>".$counter."</div>

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!