alittlecurryhot
alittlecurryhot

Reputation: 487

Animating Elements using JS

I am trying to move a div left from its original position i.e. right , the effect that i'm aiming at is that the div goes to left and then slides to the right a bit.

Vanilla JS only.

Code:

CSS:

leftBtn.addEventListener("click", function() {
    pushDiv.style.right = "420px";
    pushDiv.style.right = "360px";
    });
* {
  box-sizing: border-box;
  font-family: 'Montserrat', sans-serif;
  transition: 0.5s ease;
}

.holder{
  position: absolute;
  left: 50%;
  top: 50%;
  height: 300px;
  width: 800px;
  margin: 0 auto;
  background: #eee;
  transform: translate(-50%, -50%);
  box-shadow: 4px 9px 2px #000;
}
.push-div {
  width: 350px;
  position: absolute;
  background: #F44336;
  height: 370px;
  right: 0;
  top: -35px;
  border-radius: 5px;
}
<div class="holder">
        <button type="button" name="button" id="btn1">Left</button>
        <button type="button" name="button" id="btn2">Right</button>
        <div class="push-div" id="pushDiv">

        </div>

But on clicking on the button it shows 360px rather than giving the effect.

How do I achieve that? I have tried adding a delay but that doesn't seems to work.

Upvotes: 0

Views: 46

Answers (2)

Smokey Dawson
Smokey Dawson

Reputation: 9230

Try using css animations

JS

const pushDiv = document.querySelector('.pushdiv');

leftBtn.addEventListener('click', animate());

function animate(){
    pushDiv.addClass('animation');
{

CSS

.animation{
    animation: slideleft 0.7s ease-in; 
}

@keyframes slideleft{
    // enter your animation keyframes there are some cool tutorials that will show you how to do that same effect 
}

Upvotes: 0

JasonB
JasonB

Reputation: 6368

var leftBtn = document.getElementById('leftBtn'),
  pushDiv = document.getElementById('pushDiv');

leftBtn.addEventListener("click", function() {
  pushDiv.style.right = "410px";
  setTimeout( function() {
    pushDiv.style.right = "360px";
    }, 600 );
});
#pushDiv {
  position: absolute;
  background: red;
  top: 100px;
  right: 200px;
  width: 100px;
  height: 100px;
  transition: all .6s;
}
<button id="leftBtn">Move It</button>
<div id="pushDiv"></div>

Upvotes: 1

Related Questions