2

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

1 Answer 1

1

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);
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.