Rayleigh
Rayleigh

Reputation: 37

Why does this jQuery animation only work once?

I looked for a solution in the web, without success. I don’t understand why this code fires only once:

$("#d").click(function() {
  var h = $(".cont");
  var f = h.offset();

  if (f.left < 1) {
    h.addClass('anim');
  } else {
    h.addClass('anim2');
  }
});
body{
  margin: 0;
}

#d {
  width: 50px;
  height: 50px;
  background: #999;
}

.cont {
  width: 200px;
  height: 200px;
  opacity: 1;
  background: #333;
  position: absolute;
  -webkit-transition: all 1s ease-in-out;
}

.anim {
  -webkit-transform: translate(50px, 0px);
}

.anim2 {
  -webkit-transform: translate(0px, 0px);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="d"></div>
<div class="cont"></div>

Here’s a JSFiddle demo.

Upvotes: 1

Views: 39

Answers (1)

Smail Galijasevic
Smail Galijasevic

Reputation: 803

What you need is this

  $("#d").click( function() { 
  var h = $(".cont");
  var f = h.offset();

  if (f.left < 1) {

    h.addClass('anim');
    h.removeClass('anim2');

    } else {

    h.addClass('anim2');
    h.removeClass('anim');
  }

});

after the first click you never remove the classes so they still have effect

Upvotes: 3

Related Questions