Akanksha Mohanty
Akanksha Mohanty

Reputation: 701

Animate the div left and right using css margins in jquery

on clicking on button first time div should animate to right by 300px. When clicking 2nd time on button div should animate to left 300px. same for next click.

I have tried but it only moves to left but how can I toggle to move the div to right again?

code -

<script>
        $(document).ready(function(){
            $("button").click(function(){
                $("div").animate({ marginLeft: "300px"});
            });
        });
 </script>

<style>
    button{
        color:white;
        background-color: red;
        padding: 10px 20px;
    }
    div{
        display: inline-block;
        width: 150px;
        height: 150px;
        background-color: yellow;
        margin: 20px 50px;
    }
</style>

HTML -

<button>Click me</button>
<div>Hello</div>

Upvotes: 2

Views: 714

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337714

To achieve this use toggleClass() instead of animate() to add/remove the class on successive clicks. Then you can control the animation using transition in CSS, which performs far better than JS. Try this:

jQuery($ => {
  $("button").click(function() {
    $("div").toggleClass('right');
  });
});
button {
  color: white;
  background-color: red;
  padding: 10px 20px;
}

div {
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: yellow;
  margin: 20px 50px;
  transition: margin-left 300ms;
}

div.right {
  margin-left: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click me</button>
<div>Hello</div>

I specifically wanted to achieve the solution using Jquery Animation. Can we get the solution using Jquery animation

In this case you need to check what the current margin is and set the new value based on that. However you should note that the CSS approach above is by far the better practice to use.

jQuery($ => {
  $("button").click(function() {
    let margin = $('div').css('margin-left') == '50px' ? '300px' : '50px';
    $("div").animate({'margin-left': margin});
  });
});
button {
  color: white;
  background-color: red;
  padding: 10px 20px;
}

div {
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: yellow;
  margin: 20px 50px;
  transition: margin-left 300ms;
}

div.right {
  margin-left: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click me</button>
<div>Hello</div>

Upvotes: 1

Related Questions