How to remove (transform - translate) of an element on click?

HTML:

<div class="circle"></div>

CSS:

.circle {
  width: 30px; height: 30px;
  background: #fc4;
  display: block;
  border-radius: 30px;
  transform: translateX(0);
  transform-origin: center;
  transition: .1s ease-in-out;
}

JS: (i want to remove the circle animation on click anywhere on the document)

let circle = document.querySelector('.circle');

function comeWithMe(e) {
  let xPosition = e.clientX - 40;
  let yPosition = e.clientY - 180;

  circle.style.transform = `translateX(${xPosition}px) translateY(${yPosition}px)`;
}


window.onmousemove = comeWithMe;

3 answers

  • answered 2018-11-08 06:39 SASSY_ROG

    you can use setAttribute or removeAttribute

    removeAttribute

    setAttribute

    document.getElementById('para').addEventListener('click', function() {
      document.getElementById('para').setAttribute('style', 'display:none');
    });
    
    document.getElementById('para2').addEventListener('click', function() {
      document.getElementById('para2').removeAttribute('style', 'color');
    });
    <p id='para'>clickme</p>
    <p id='para2' style='color:red'>clickme too</p>

  • answered 2018-11-08 06:43 Will

    This will move it back to the origin. I think that's what you wanted.

    let circle = document.querySelector('.circle');
    let move = true;
    
    function comeWithMe(e) {
      let xPosition = move ? e.clientX - 10 : 0;
      let yPosition = move ? e.clientY - 10 : 0;
    
      circle.style.transform = `translateX(${xPosition}px) translateY(${yPosition}px)`;
    }
    
    window.onmousemove = comeWithMe;
    window.onclick = function(e) {
      move = !move;
      comeWithMe(e);
    }
    .circle {
      width: 30px;
      height: 30px;
      background: #fc4;
      display: block;
      border-radius: 30px;
      transform: translateX(0);
      transform-origin: center;
      transition: .1s ease-in-out;
    }
    <div class="circle"></div>

  • answered 2018-11-08 06:50 Nilesh Naik

    This will end the animation if you click anywhere in the document. onclick i am removing the mousemove event.

    let circle = document.querySelector('.circle');
    
    function comeWithMe(e) {
      let xPosition = e.clientX - 40;
      let yPosition = e.clientY - 40;
      circle.style.transform = `translateX(${xPosition}px) translateY(${yPosition}px)`;
    }
    window.addEventListener("click", function(event) {
      window.removeEventListener("mousemove", comeWithMe);
    });
    window.addEventListener("mousemove", comeWithMe);
    .circle {
      width: 30px;
      height: 30px;
      background: #fc4;
      display: block;
      border-radius: 30px;
      transform: translateX(0);
      transform-origin: center;
      transition: .1s ease-in-out;
    }
    <div class="circle"></div>