In jQuery, the offset()
method returns an object containing the properties top
and left
, which specify the current offsets of the element with respect to the whole document. This method can be used either as a getter or as a setter. In this post I'll show you a practical example which makes use of this method for creating a simple drop down menu.
Suppose that we have a markup structure like the following:
<ul id="navigation"> <li><a href="#">Home</a></li> <li class="sub"> <a href="#">About</a> <ul> <li><a href="#">Us</a></li> <li><a href="#">Our projects</a></li> <li><a href="#">This site</a></li> </ul> </li> <li><a href="#">Contacts</a></li> </ul>
The submenu has to be shown exactly under the active list item when a user hovers the corresponding link. Here's how we can do with jQuery:
$(function() { $('li.sub', '#navigation').each(function() { var $li = $(this); var $a = $li.find('a:first'); var height = $li.parent().height(); var left = $a.offset().left; $li.find('ul').css('opacity', 0); $a.mouseover(function() { $a.next().offset({top: height, left: left}).animate({ opacity: 1 }, 'slow'); }); $a.next().mouseleave(function() { $(this).animate({ opacity: 0 }, 'slow', function() { $(this).css('top', '-1000em'); }); }); }); });
As you can see, the offset()
method is first used as a getter to obtain the left offset of the active link and then used as a setter to absolutely position the submenu just under the active item. The syntax used above is the normal syntax used for all the JavaScript object literals. You can see a demo below.