Martin Štefek
Martin Štefek

Reputation: 358

Stop scrolling to every clicked link one after one, scroll just to the first clicked link

I need to fix my code. If I will click on more than one html href link in menu my script will scroll to every one clicked link one after one clicked links. I need to scroll just to the first clicked link and another clicked links during the scrolling function will be ignored.

jQuery(window).bind("load", function () {
var hash = window.location.hash;

hash = hash.replace("#", "");

var elem = jQuery(".pb-line-css-group-" + hash);

menu_scroll_to(elem);
});

jQuery(document).ready(function () {

jQuery(".menu-item A").click(function () {
    var hash = jQuery(this).attr('href');

    hash = hash.replace("#", "");
    hash = hash.replace("/", "");

    var elem = jQuery(".pb-line-css-group-" + hash);

    menu_scroll_to(elem);
});
});

function menu_scroll_to(elem) {

if (elem) {
    jQuery('html, body').animate({
        scrollTop: elem.offset().top - 70
    }, 2000, "easeOutQuint");
}

}

Upvotes: 0

Views: 68

Answers (1)

Ryan Gill
Ryan Gill

Reputation: 1758

You could set up a debounce function so that you only call menu_scroll_to() one time for multiple clicks within a set period of time.

Here is a link to a debounce function that should work.

Debounce function

add that function to your JS and replace the following line:

menu_scroll_to(elem);

with:

debounce(function() {
    menu_scroll_to(elem);
}, 250);

where 250 is the time in milliseconds.

final code all together would be something like this:

jQuery(window).bind("load", function () {
        var hash = window.location.hash;

        hash = hash.replace("#", "");

        var elem = jQuery(".pb-line-css-group-" + hash);

        menu_scroll_to(elem);
});

jQuery(document).ready(function () {

        jQuery(".menu-item A").click(function () {
                var hash = jQuery(this).attr('href');

                hash = hash.replace("#", "");
                hash = hash.replace("/", "");

                var elem = jQuery(".pb-line-css-group-" + hash);

                debounce(function () {
                    menu_scroll_to(elem);
                }, 250);
        });
});

function menu_scroll_to(elem) {
    if (elem) {
            jQuery('html, body').animate({
                    scrollTop: elem.offset().top - 70
            }, 2000, "easeOutQuint");
    }
};

function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

Upvotes: 1

Related Questions