Reputation: 1156
I'm having a container containing a top menu. But when this container is scrolled by width 60 px I need a class to be added to the top menu, but it doesn't do it now.
I have this Jquery:
$( window ).scroll(function() {
if ($('#case-container').scrollTop()>60) {
$('.case-header').addClass('sticky')
} else if ($('#case-container').scrollTop()<60) {
$('.case-header').removeClass('sticky')
}
});
How can I fix this to make it work?
Upvotes: 0
Views: 1518
Reputation: 318182
The elements scrollTop doesn't change, only the element that is being scrolled will have the scrollTop changed.
Note that for setting the scrollTop, some browsers use body, other html, so the usual fix is to check both like so $('body, html').scrollTop(100)
, but for getting, window (or in this context this
) should work :
$( window ).scroll(function() {
if ($(window).scrollTop()>60) {
$('.case-header').addClass('sticky')
} else if ($(window).scrollTop()<60) {
$('.case-header').removeClass('sticky')
}
});
As a sidenote, you could shorten it to
$(window).on('scroll', function() {
$('.case-header').toggleClass('sticky', $(this).scrollTop() > 60);
});
Upvotes: 1