1

I have a one page website with a fixed menu button, the website has multiple sections:

<div class="fullscreen sec-1"></div>
<div class="fullscreen sec-2"></div>
<div class="fullscreen sec-3"></div>

By default the text for the button is white as the background colour of the first div is black. The colour of the second and third is white, so I want the colour of the button text to change to black when the scroll hits the top of the second div. I have managed to achieve this with if else but the height is fixed so when its on mobile devices the outcome is different because the height of the divs are all 100% fullscreen. I changed my code to:

$(document).ready(function() {
        var button = $(".sec-1");
        var offset = button.offset();
        $(function () {
            $(window).scroll(function () {
                if ($(window).scrollTop() >= offset) {
                    $(".menu-button").css("color","black");
                } else {
                    $(".menu-button").css("color","white");

                }
            });
        });
});

Currently I'm having no luck, and I'm struggling to find an example to refer to so if anyone could help me or point me in the right direction I'd be very grateful.

2
  • 1
    I think it's better provide a simple live demo. add some html and css. think it's kinda unclear. Commented Dec 12, 2017 at 17:50
  • Try to create a minimal reproducible example so we can see the actual problem. Commented Dec 12, 2017 at 18:24

1 Answer 1

2

.offset()

.offset() returns an object containing the properties top and left.

and you should be checking for .sec-2 instead of .sec-1

Try something like

$(document).ready(function() {
        var button = $(".sec-2"); //get offset of second div
        var offset = button.offset().top; //check for top property
        $(function () {
            $(window).scroll(function () {
                if ($(window).scrollTop() >= offset) {
                    $(".menu-button").css("color","black");
                } else {
                    $(".menu-button").css("color","white");

                }
            });
        });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. The missing 'top' and getting offset for the second div was correct.

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.