w3resource

jQuery: Animate the first division's left property and synchronizes the remaining divisions

jQuery Fundamental - I : Exercise-21

Using jQuery animates the first div's left property and synchronizes the remaining divs.

Note: Use the step function to set their left properties at each stage of the animation.

<body>
<p><button id="run">Click to Run »</button></p>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
</body>
div {
    position: relative;
    background-color: #B0E0E6;
    width: 45px;
    height: 45px;
    float: left;
    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 the first div's left property and synchronizes the remaining divs.</title>
</head>
<body>
<p><button id="run">Click to Run »</button></p>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
</body>
</html>

CSS Code:

div {
    position: relative;
    background-color: #B0E0E6;
    width: 45px;
    height: 45px;
    float: left;
    margin: 5px;
  }

JavaScript Code :

$( "#run" ).click(function() {
  $( ".block:first" ).animate({
    left: 100
  }, {
    duration: 2000,
    step: function( now, fx ){
      $( ".block:gt(0)" ).css( "left", now );
    }
  });
});

Used Methods :

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

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


Contribute your code and comments through Disqus.

Previous: Using jQuery animates a div's left property with a relative value.
Next: Using jQuery change the color of any div that is animated.

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-21.php