This simple code snippet helps you customize the scrolling event on your HTML web page. It tracks each scroll.
This would be very handy when designing a single page application.
Now-a-days when user scrolls on the Single page application, the navigation link changes class and displays the user.
Use the snippet andl et me know:
function onScroll() {
var scrollPos = $(document).scrollTop();
$('.navbar .navClick').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position() != undefined && refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('.navbar .navClick').removeClass("active");
currLink.addClass("active");
}
else {
currLink.removeClass("active");
}
});
}$(document).on('click', '.navClick', function (event) {
event.preventDefault();
var target = "#" + this.getAttribute('data-target');
$('a').each(function () {
$(this).removeClass('active');
});
$(this).addClass('active');
$('html, body').animate({
scrollTop: $(target).offset().top + 70
}, "slow", "linear", function () {
$(document).on("scroll", onScroll);
});
});The second snippet helps you detect the ID clicked and then help you toggle the active class for the nav link clicked. We need to add data-target on the HTML element in order to track the click and animate the User to the selected div on click.Hope this helps.
