1

I am trying to add a class to the header if the user scrolls past the div #home - and remove the class when you scroll back to the top.

The issue is, when you scroll past the div it adds the class but when you keep scrolling and then scroll back up, the class does not get removed. The event is only firing once...

I created this jsFiddle here - https://jsfiddle.net/breezy/9evksr7y/

It works in my jsFiddle file but not on my actual web page, I've also tried this...

$(window).on( 'scroll', function() {

        var header = $('#header'),
            target = $("#home").offset().top;

        var interval = setInterval(function() {
            if ($(window).scrollTop() > 400) {
                // alert("made it!");

                header.addClass('fixed');  

                clearInterval(interval);

            } else {

                header.removeClass('fixed');

            }

        }, 250);


    });

But it still does not work. Any idea what I am doing wrong?

Thanks


Edit: The issue was that one of my other functions in the same document was conflicting w/ this scroll function.

2
  • Why are you using setInterval()? Commented May 17, 2016 at 23:32
  • I was using this as a reference - stackoverflow.com/a/5036892/745617 @Mikey Commented May 17, 2016 at 23:33

1 Answer 1

2

So I made some minor tweaks to the code. Not sure what the issue was but this seemed to work for me on my webpage.

$(window).on('scroll', function() {

  var header = $('#header'),
    target = $("#home").offset().top;

    if ($(window).scrollTop() > target) {

      header.addClass('fixed');

    } else {

      header.removeClass('fixed');

    }

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

1 Comment

Hey thanks... you know what the issue was, one of my other functions was conflicting w/ my scroll function. Thanks anyway @timerewinder

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.