Use jQuery to create a floating navigation based on scrolling
I didn’t know what else to call this post other than “Use jQuery to create a floating navigation based on scrolling”! If this doesn’t make sense let me describe want we will be creating. Hopefully after that things will become clearer.
Have you ever seen a site where when you scroll an object on the page just seems to magically follow you? Most of the time this sort of thing is done with Ads so the ad is in your face. How do these guys do that?
We will be looking at this but instead of using ads we are going to have our navigation area so that it’s always visible. As an extra bonus we’ll make our animated when it moves and we’ll make sure that it’s animation is as smooth as glass.
Before getting into thing you will need to know about the scroll function in jquery. Basically when ever you scroll and event will be made letting the script know that you’ve scrolled. While this is good when we scroll we’ll probably set off 100 or so scrolls in a very short span. Because of the amount of events created it can slow things down and make things choppy because it has to redraw after each event.
So how do we first of all code this and secondly how do we prevent the choppiness? I thought you’d never ask! Let’s look at the code:
Ok the HTML should be really self explanatory. I will go over the CSS and jQuery.
Because I want to use positioning I give #navigation an absolute position of top – right on the page( Naigation will have a 5px padding). I also want it to hover over anything else (if the page is made smaller) so I gave it the highest z-index on the page. All links will be aligned to the right and I applied a background color to match the example above.
First off I make sure that the page is ready. Next I want to grab jQuery’s “Window” element. I tell jQuery that when ever the Window scrolls to send an event. Now that we know that the scroll even happens we should do some magic on #navigation
Let’s select #navigation. Stop any animation that might be going on with it. Then let’s animate it. You might be asking why I ran stop. As you are scrolling you might send 20-40 events in a second to the browser. This means that jQuery has to do a ton of math. This will make things look jerky. To avoid this I just say… Stop let the browser do what it wants when the person stops start the animation.
If you’ve read some of my previous jQuery tutorials you might remember going over how animate works. The first section basically says: Assign the element top (This refers to the CSS position element “Top”) a value of what ever the documents Top position is.
The second part basically tell the animation how long to animate things for and what animation you want to use.
Try it out! It’s amazing how smooth jQuery can actually run when the code is clean!