Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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%)
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading