Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda