My goal is to use jQuery to create a sticky header div (with position: fixed) once it's scrolled past a certain point.
This code has been working well for me:
$(window).scroll(function() {
var y = $(this).scrollTop();
if (y >= 200) {
$('.top').addClass('sticky');
} else {
$('.top').removeClass('sticky');
}
});
However, I wanted to improve the user experience so I began experimenting with jQuery UI. Here is where I encountered an issue:
$(window).scroll(function() {
var y = $(this).scrollTop();
if (y >= 200) {
$('.top').toggle('fade', 200, function() {
$('.top').addClass('sticky', function() {
$('.top').toggle('fade', 200);
});
});
} else {
$('.top').removeClass('sticky');
}
});
The desired behavior is for the div to fade out, become sticky, and then fade back in. However, it seems to be continuously toggling the fade effect.
Can someone offer advice on how to achieve the intended behavior? I want it to trigger once it's scrolled past the specified point, rather than constantly reacting to the scroll position.
Thank you.