- Inserting Elements
- Creating a Lightbox Effect
- More Fun with DOM Manipulators
- Getting and Setting Measurements
- Cloning
- Changing an Input Element
- Rewind and Review
Getting and Setting Measurements
There are some DOM manipulators whose sole purpose is to help you get and set measurements. Let’s use a couple of those to help animate a floating menu.
To use scrollTop() and offset() to create a floating menu
- Modify the markup of article.html first by adding a div to wrap the div with an id="content"(Script 4.3.html):
<div class="pageWrapper"> <div id="content"> // all of the content is here </div> </div>
- Add the following markup to define the floating menu. It must be within the pageWrapper div:
<div class="sidebar"> <a href="article.html"> Articles</a><br /> <a href="gallery.html"> Photo Gallery</a> </div>
- Save article.html and upload it to your web server.
- Create the jQuery function to make the menu float in jquery.custom.js:
var sidebarOffset = $('.sidebar').offset(); var paddingTop = 10; $(window).scroll(function() { if ($(window).scrollTop() > sidebarOffset.top) { $('.sidebar').stop() .animate({ marginTop: $(window).scrollTop() - sidebarOffset.top + paddingTop }); } else { $('.sidebar').stop() .animate({ marginTop: $(window).scrollTop() }); } });
- Save jquery.custom.js and upload it to your web server.
- Load article.html into your web browser and you’ll see the floating menu on the right-hand side of the page .
As you scroll down the page, the menu will float into place .
Let’s see what’s behind the curtain on making this little function work. First you save the sidebar’s offset to a variable. The offset() function gets the current position of an element relative to the document. The function returns an object having two properties: top and left .
The other measurement you took is the window’s scrollTop() amount. This measurement, in pixels, is the number of pixels hidden from view above the browser window as you scroll down the page .
Once the scroll event takes place, all you have left to do is to animate the div into its new position (you’ll read more about animations in Chapter 8). You’ll do that based on the measurement provided by scrollTop(). Then you do a little math to subtract the original offset amount and add in a padding value to make sure the div is 5 pixels below the edge of the top of the browser window .