jQuery: switching element positions

jQuery allows us to get the offset of an element through its offset() wrapper which, in turn, returns the left and top offsets of an element. We can use this wrapper to create the effect of elements that switch their positions on the page. Also, we can further enhance this effect by adding other style properties to the animate() method. For example:

$(document).ready(function() {

  var endOffset = $('#target').offset().top;
  $('#test').click(function() {
      top: endOffset,
      width: 225
    }, 500, function() {
        top: - endOffset,
        width: 225
      }, 500);

When we click on the first element, both element positions are switched, with the first element now taking the position of the second. We've used the top property of the offset() wrapper to get the exact top offset of the first element. Then we've used this offset with the animate() method by also modifying the element dimensions. You can see the demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.