最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Prevent clicking a link if scroll on mobile - Stack Overflow

programmeradmin5浏览0评论

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?

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?

Share Improve this question edited Jul 5, 2016 at 20:53 Zakaria Acharki 67.5k15 gold badges78 silver badges106 bronze badges asked Jul 5, 2016 at 13:20 momciloomomciloo 9471 gold badge11 silver badges25 bronze badges 2
  • did you change the touch behavior? On my phone if I start scrolling on a link then the link doesn't get triggered... – Simon Hänisch Commented Jul 5, 2016 at 13:26
  • In my own experience on mobile browsing I have run into this problem before - Upvote. I have not expended any effort to try to curb this behavior, but off the top of my head. You could possibly create a larger element that seperates the actual link and the rest of the item. Will look at this post closely... – Terrance00 Commented Jul 5, 2016 at 13:27
Add a ment  | 

1 Answer 1

Reset to default 7

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.

发布评论

评论列表(0)

  1. 暂无评论