Moving a div into the screen area smoothly using JQuery and the window onscroll event

Posted: 11th June 2010 in JQuery
Tags:

My latest user requirement with my on-going accordion control application: the user wanted the DIV containing the navigation, tree view, user control must always be in view.

So, here’s how I went about it, along with some of the pitfalls I found along the way.

Scrolling a Div
  1. var scrollId = 0;
  2.            var SCROLL_DELAY = 500;  // Acceptable delay for scrolling to stop
  3.            $(window).scroll(function() {
  4.                setTimeout('moveNavigationDiv()', SCROLL_DELAY);
  5.            });
  6.  
  7.            // Moves the navigation div relataive to the page on scroll of the main window
  8.            function moveNavigationDiv() {
  9.                var now = new Date();
  10.                if (scrollId == 0 || (parseInt(parseInt(scrollId) + parseInt(SCROLL_DELAY)) < now.getTime())) {
  11.                    $("div[id$='navigation']").css({ 'position': 'relative' })
  12.                    $("div[id$='navigation']").animate({ "top": $("html").scrollTop() }, "1000", "linear");
  13.                    scrollId = now.getTime();
  14.                }
  15.            }

Firstly, I though this would be fairly straight forward. However, what I never realised was that the windows.onscroll event fires constantly as you are scrolling, not once as I thought. I suppose, when I think about it, this makes sense.

Because of this I had to try and pre-empt when the scrolling has stopped. For this I added a delay of 0.5 seconds.  If you don’t add this delay the control does move to the correct position, but it does it in a jerky motion, which doesn’t look very good.  Adding the delay allows the function to know what the final position is before it moves, making it a smooth movement.

To ensure the animating part of the  moveNavigationDiv()  only gets called once I’ve added a variable, scrollId,  which is updated in the if statement after a comparison with the SCROLL_DELAY and the current time.

I could have just used the CSS top: property to update the position of the div, but I had a little extra time and decided to use the JQuery animate instead to make it a bit easier on the eye.

Advertisements
Comments
  1. I’ve recently started a blog, the information you provide on this site has helped me tremendously. Thank you for all of your time & work.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s