Max Lynn Max Lynn - 1 month ago 8
Javascript Question

prevent code from being called if a click event has been triggered

I have this very simple click event that triggers a scroll to an ID that has been clicked that you can see below:

$('.navigation-panel a').on('click', function () {
var id = $(this).attr('href');
$('html, body').animate({ scrollTop: $(id).offset().top - 100 }, 1000);
});


When this gets fired it also triggers my other scroll event that you can see here:

$(window).scroll(function () {
var y = $(this).scrollTop();

menu.each(function (event) {
if (y >= $($(this).attr('href')).offset().top - 100) {
menu.not(this).removeClass('active');
$(this).addClass('active');
}
});

});


The question that I'd like to be answered is how do I prevent the second script from being executed if the click event has already happened? However I need the second script to fire after the click event has finished.

The scripts have to be separate as the second script is important for when a user is just scrolling and not clicking to navigate to different parts of the page.

Answer

One sure way to not trigger the event handler when clicking, would be to temporarily remove the event handler, and then when the animation has ended attach the event handler again and trigger it.

$(window).on('scroll', scroller);

function scroller() {
    var y = $(this).scrollTop();

    menu.each(function(event) {
        if (y >= $($(this).attr('href')).offset().top - 100) {
            menu.not(this).removeClass('active');
            $(this).addClass('active');
        }
    });
}

$('.navigation-panel a').on('click', function() {
    var id = $(this).attr('href');

    $(window).off('scroll', scroller);

    $('html, body').animate({
        scrollTop: $(id).offset().top - 100
    }, 1000, function() {
        $(window).on('scroll', scroller).trigger('scroll');
    });
});