0

I need help with the following, i have a menu that i want to stay fixed when the page scrolls down.The first part of the page is white and then after some 800px all the rest is black background. I want to be able to change the color of the menu to white when the user scrolls into the black section. I know how to change it by adding and removing classes in jQuery, but i am having problems writing code how to detect how many of the page is scrolled. I believe it should be some simple if statement calculating the top offset, but i really cant solve it myself.

Thanks, Mirko

4 Answers 4

1
$(document).scroll(function(){
    if($(document).scrollTop() >= max) {
        // do something
    }
})
Sign up to request clarification or add additional context in comments.

Comments

0

$(window).scrollTop() will give you the amount of pixels a user has scrolled.

You should really post some example code if you want some more elaborate assistance.

Comments

0

You can compare

$("#menu").offset().top

to

$("#blackDiv").offset().top

If the former is larger than the latter, then change the menu color and if not, change it back.

This handles future changes to the layout of your page (i.e. if the black section of the page stops being exactly 800px from the top).

Comments

0

Here's an example using offset().top as suggested by @bricriu.

HTML:

<div id="menu"> MENU </div>
<div class="darkBackground">
</div>
<div class="lightBackground">
</div>

CSS:

.darkBackground{height:400px; background-color:black;}
.lightBackground{height:400px; background-color:yellow;}
#menu{height:30px; width:100%; position:fixed; background-color:red; top:150px; color:white;}
#menu.darkMenu{background-color:green;}

Javascript:

$(window).scroll(function () { 
    console.log("menu: "+$("#menu").offset().top+" background: "+$(".lightBackground").offset().top);
    if($("#menu").offset().top > $(".lightBackground").offset().top){
        $("#menu").addClass("darkMenu");
    }else{
        $("#menu").removeClass("darkMenu");      
    }
});

In this example the menu toggles from green to red where the background changes from black to yellow.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.