0

in my js code I have pretty simple event listener listening for a click -

element.addeventlistener('click', ()=>{
#do somthing
})

the issue is that when I am scrolling on IOS (iphone) - touching this element to start the scroll, triggers the event listener.

Is there a way to prevent a event listener on iphone, unless no scrolling is to follow?

i.e. do something if clicked but scrolling doesn't follow


alternatively the might be a completely different solution (but I am trying to avoid a library)

thanks W


ANSWER

After reviewing the answer given below (which does work) as described, this issue was still persisting. This gave me cause to review my CSS on which I found that on IOS mobile (iphone) - the CSS psudo selector :focus is activated when you scroll over an item.

I added a media query to only allow :focus to be used on desktop size devices or above, which solved the issue.

Wally
  • 459
  • 4
  • 15

2 Answers2

1

I'm not an expert, but I would try:

var prevScroll = pageYOffset;
window.addEventListener("scroll", () => prevScroll = pageYOffset);
window.addEventListener("click", (e) => {
  if (pageYOffset !== prevScroll) return;

  // your code
});

Please note that this code is not tested, however I think it should work.

Jacob Lockwood
  • 380
  • 1
  • 12
1

I have a found a possible solution on another question in Stackoverflow: Question

Basically you add a scroll listener to your window. This will then set a global boolean called disable_click_flag to true when scrolling. If the user wasn't scrolling for at least 250ms it will be set to false.

When the boolean is true then the click event isn't able to go trough.

var disable_click_flag = false;
var timeout = null;

window.addEventListener('scroll', () => {
  disable_click_flag = true;

  if(timeout) clearTimeout(timeout);
  
  timeout = setTimeout(function(){ disable_click_flag = false }, 250);
}

element.addeventlistener('click', () => {
  if(disable_click_flag === false{
    #do somthing
  }
})
Stephen
  • 338
  • 5
  • 18