w3resource

jQuery: Animate a division's left property with a relative value

jQuery Fundamental - I : Exercise-20

Using jQuery animates a div's left property with a relative value.

<body>
<button id="left"><</button>
<button id="right">></button>
<div class="block"></div>
</body>
div {
    position: absolute;
    background-color: #B0E0E6;
    left: 40px;
    width: 80px;
    height: 80px;
    margin: 5px;
  }

Sample solution :

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Animates a division left property with a relative value.</title>
</head>
<body>
<button id="left">&lt;</button>
<button id="right">&gt;</button>
<div class="block"></div>
</body>
</html>

CSS Code:

div {
    position: absolute;
    background-color: #B0E0E6;
    left: 40px;
    width: 80px;
    height: 80px;
    margin: 5px;
  }

JavaScript Code :

 $( "#right" ).click(function() {
  $( ".block" ).animate({ "left": "+=50px" }, "slow" );
});
 
$( "#left" ).click(function(){
  $( ".block" ).animate({ "left": "-=50px" }, "slow" );
});

Used Methods :

  • .animate() : Perform a custom animation of a set of CSS properties.

See the Pen jquery-fundamental-exercise-20 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Using jQuery click the button to animate the paragraph element with a number of different properties.
Next: Using jQuery animates the first div's left property and synchronizes the remaining divs.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/jquery-exercises/1/jquery-fundamental-exercise-20.php