Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have long vertical list of links that user can scroll through, and I need to prevent triggering a click event (touch) on this links if user scrolls.

In current scenario, when user start scrolling by tapping over the link, it also triggers a click on link. Which is obviously bad. So, is there any way to prevent such a behavior?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
316 views
Welcome To Ask or Share your Answers For Others

1 Answer

Working fiddle

We could use a flag in this case to prevent click event just during the scroll and enable it after the scroll stop.

To listen on scroll stop you could use jQuery’s data method that gives us the ability to associate arbitrary data with DOM nodes and using setTimeout() function that will check every 250ms if the user still trigger the scroll, and if not it will change the flag :

var disable_click_flag = false;

$(window).scroll(function() {
    disable_click_flag = true;

    clearTimeout($.data(this, 'scrollTimer'));

    $.data(this, 'scrollTimer', setTimeout(function() {
        disable_click_flag = false;
    }, 250));
});

$("body").on("click", "a", function(e) {
    if( disable_click_flag ){
        e.preventDefault();
    }
});

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...