Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
This chapter is from the book

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

  1. 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
  2. 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>
  3. Save article.html and upload it to your web server.
  4. 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() > {
    marginTop: $(window).scrollTop() - + paddingTop
    } else {
    marginTop: $(window).scrollTop()
  5. Save jquery.custom.js and upload it to your web server.
  6. Load article.html into your web browser and you’ll see the floating menu on the right-hand side of the page red-a.jpg.

    Click to view larger image

    red-a.jpg The new menu is ready to go.

    As you scroll down the page, the menu will float into place red-b.jpg.


    Click to view larger image

    red-b.jpg The menu floats into view as lightly as a cloud.

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 red-c.jpg.


Click to view larger image

red-c.jpg An example of offset for two elements.

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 red-d.jpg.


Click to view larger image

red-d.jpg The scrollTop() method measures what you can’t see.

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 red-e.jpg.


Click to view larger image

red-e.jpg The original gap is maintained after the animation.

  • + Share This
  • 🔖 Save To Your Account