Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

jQuery offset() or position()—Change an element's properties when close to another element

jQuery offset() or position()—Change an element's properties when close to another element

Problem

I want to have a Nav Bar set position: fixed to the top of my window, with links that smooth scroll to different sections.

I've got the smooth scrolling parts working just fine. Next, I want to change the colour of the navbar as it scrolls down the screen. I'd like things to switch/animate something like this:

When scrolled down to Section2 = Animate to a YELLOW Navbar When scrolled down to Section3 = Animate YELLOW > RED Navbar

I could easily achieve this effect via the click method (when the click on #section2, change the CSS), but how would I get it to change if users scrolled down the screen—without using the links in the nav bar?

Where I've gotten so far: http://jsfiddle.net/saltcod/4xkbs/2/

Thanks!

Terry

Problem courtesy of: saltcod

Solution

You can handle the scroll event, then in your event handler, get the offset for the sections to see if the y coordinate is at or above the nav list. Something like:

$(window).scroll(function() {
    var bottom = $("#navcontainer").offset().top + $("#navcontainer").offset().height();
    if ($("#section3").offset().top 

Binding to $(window).scroll in jsFiddle doesn't appear to work, so I haven't tested this code.

Solution courtesy of: dgvid

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

jQuery offset() or position()—Change an element's properties when close to another element

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×