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>
CodePudding user response:
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>
CodePudding user response:
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>