Home > Mobile >  change position on click-javascript animation
change position on click-javascript animation

Time:01-22

How can I create a button to change a div's position on first click with 2sec transition and bring it back on the second click.

I did this but it doesn't bring it back.

var d = document.getElementById("button");
d.addEventListener('click', function() {
  d.className = d.className   " move";
});

CodePudding user response:

Better call is d.classList.toggle("transitionClassName")

I copied the transitions from CSS transition between left -> right and top -> bottom positions

var d = document.getElementById("button");
d.addEventListener('click', function() {
  d.classList.toggle("move");
  d.classList.toggle("right");
});
.animate {
  height: 100px;
  width: 100px;
  background-color: #c00;
  transition: all 1s ease;
  position: absolute;
  cursor: pointer;
  font: 13px/100px sans-serif;
  color: white;
  text-align: center;
}


/* ↓ just to position things  */

.animate.left {
  left: 0;
  top: 50%;
  margin-top: -100px;
}

.animate.right {
  right: 0;
  top: 50%;
}

.animate.top {
  top: 0;
  left: 50%;
}

.animate.bottom {
  bottom: 0;
  left: 50%;
  margin-left: -100px;
}

.animate.left.move {
  left: 100%;
  transform: translate(-100%, 0);
}

.animate.right.move {
  right: 100%;
  transform: translate(100%, 0);
}

.animate.top.move {
  top: 100%;
  transform: translate(0, -100%);
}

.animate.bottom.move {
  bottom: 100%;
  transform: translate(0, 100%);
}
<button type="button" id="button" >Move</button>

CodePudding user response:

const d = document.getElementById("button");

d.style.transition = "0.8s";

d.addEventListener('click', function(event) {
    event.target.classList.toggle("move");
});
.move {
  margin-left: 50px;
}
<button id="button">Click Me!</button>

  •  Tags:  
  • Related