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

240
Vistas
How to toggle between 2 css class using javascript?

Refering to a live demo codepen at https://codepen.io/Maximusssssu/pen/MWrzpav. May I ask how can I toggle between 2 css class that is red square and red triangle represented below? When user click on triangle button, it will represent a triangle when grid is clicked and when click on square button it will be a square on grid when user click on it. Thank you for reading and have a nice day :)

  <button onclick="triangle()">triangle</button>
  <button onclick="square()">square</button>



.red-dot {
  position:absolute; 
  width:15px; 
  height:15px;
  background:red;
  pointer-events: none;
}
.red-triangle {
  position:absolute; 
  width:15px; 
  height:15px;
  background:red;
  pointer-events: none;
  clip-path: polygon(50% 0, 100% 100%, 0 100%)
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Here you go:

let classNameValue = "red-dot"

function triangle(){
  classNameValue = "red-triangle"
}

function square(){
  classNameValue = "red-dot"
}

I just created a global variable and I set it to the className value you need, and then I just set the newDot.classList to the variable value.

function showCoords(event) {
    // Calculate the position of the nearest grid intersection:

   var x = (Math.floor(event.clientX/50) * 50)+2 ;
   var y = (Math.floor(event.clientY/50) * 50)+2 ;
    var coords = "X coordinates: " + x + ", Y coordinates: " + y;
    document.getElementById('showCoords').innerHTML = coords;
    // Create a new red dot:
    let newDot = document.createElement('span');
    // Add the CSS class:
    newDot.className = classNameValue;
    // Set coordinates:
    newDot.style.top = y + 'px';
    newDot.style.left = x + 'px';
    // Add the new element to the end of the body:
    document.body.appendChild(newDot);
  }
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