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() { $(this).animate({ top: endOffset, width: 225 }, 500, function() { $('#target').animate({ 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.