Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery animation don't work after two clicks

I was trying working on animation through jQuery and I faced a problem that the div box work for only 2 clicks. Any kind of help is appreciated. Here is my code:

$(document).ready(function() {
  $("#one").click(function() {
    $("div").animate({
      top: '250px'
    });
  });

  $("#sec").click(function() {
    $("div").animate({
      bottom: '250px'
    });
  });

  $("#thi").click(function() {
    $("div").animate({
      right: '250px'
    });
  });

  $("#for").click(function() {
    $("div").animate({
      left: '250px'
    });
  });
});
.box {
  background: grey;
  height: 20px;
  width: 20px;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="one">DOWN</button>
<button id="sec">TOP</button>
<button id="thi">LEFT</button>
<button id="for">RIGHT</button>

<br><br>
<div class="box">
</div>

Here is my code link: https://jsfiddle.net/djmayank/mcutmbcy/1/

like image 924
djmayank Avatar asked Aug 06 '17 18:08

djmayank


1 Answers

Updated fiddle.

You could "increase/decrease" just the top/right offsets using += and -= :

$(function(){
    $("#one").click(function(){
        $("div").animate({top: '+=25px'});
    });
    $("#sec").click(function(){
        $("div").animate({top: '-=25px'});
    });
    $("#thi").click(function(){
        $("div").animate({right: '+=25px'});
    });
    $("#for").click(function(){
        $("div").animate({right: '-=25px'});
    });
});

NOTE : You could use just one ready function.

Hope this helps.

$(document).ready(function(){
  $("#one").click(function(){
      $("div").animate({top: '+=100px'});
  });
  $("#sec").click(function(){
      $("div").animate({top: '-=100px'});
  });
  $("#thi").click(function(){
      $("div").animate({right: '+=100px'});
  });
  $("#for").click(function(){
      $("div").animate({right: '-=100px'});
  });
});
.box{
  background:grey;
  height:20px;
  width:20px;
  position:absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="one">DOWN</button>
<button id="sec">TOP</button>
<button id="thi">LEFT</button>
<button id="for">RIGHT</button>

<br><br>
<div class="box">
</div>
like image 196
Zakaria Acharki Avatar answered Oct 07 '22 00:10

Zakaria Acharki