Listen to scroll events with $(window).on('scroll', fn). Use scrollTop() to read position and toggle classes for sticky navbars. Always debounce the scroll handler to avoid performance problems from rapid firing.
Scroll Handling
$(window).on('scroll', function() {
const top = $(this).scrollTop();
if (top > 100) {
$('#navbar').addClass('sticky');
} else {
$('#navbar').removeClass('sticky');
}
});
// Smooth scroll to element
$('a[href^="#"]').on('click', function(e) {
e.preventDefault();
$($(this).attr('href'))[0].scrollIntoView({ behavior: 'smooth' });
});