Scrolling triggers the click event

Within my JavaScript code, I have a rather simple event listener set up to listen for a click:

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

However, I am encountering an issue on IOS (iPhone) where scrolling triggers the event listener when touching the element to start the scroll.

Is there a way to prevent the event listener on iPhone unless there is no scrolling following the click?

Essentially, I want to execute a function if clicked without triggering it when scrolling occurs.


Alternatively, there may be a different solution to explore without relying on a library.

Thank you, W


ANSWER

Despite trying the solution provided below (which did work to some extent), the issue persisted. This prompted me to inspect my CSS code, where I discovered that on IOS mobile devices, the CSS pseudo selector :focus is activated while scrolling over an item.

To resolve this, I implemented a media query to restrict the use of :focus to desktop-sized devices and above, effectively resolving the issue.

Answer №1

I stumbled upon a potential fix for this issue on a different post on Stack Overflow: Question

The solution involves adding a scroll listener to the window. This listener will set a global boolean named disable_click_flag to true while scrolling. If the user has not scrolled for at least 250ms, the flag will be set back to false.

When the flag is true, the click event will not be allowed to pass through.

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
  }
})

Answer №2

While I'm not a professional, you could attempt the following approach:

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

  // insert your code here
});

Disclaimer: This code is untested, but I believe it has the potential to be effective.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passing backend variables/data to AngularJS in Express JS

As a newcomer to express js, I appreciate your patience with me. I've been diving into "MEAN Web Development" by Amos Q. Haviv and finding it to be an excellent read. However, there's one part that's leaving me puzzled. It seems that in or ...

Contrasting memory management techniques on iOS devices versus the iPhone simulator

I have noticed inconsistencies in memory management between the iOS simulator and actual iOS devices. Sometimes, a crash occurs on a device when attempting to access an object that no longer exists, but this issue doesn't appear on the simulator (wher ...

When using addClass("test"), it throws an error message: TypeError: undefined is not a function

Upon examination in the console, I discovered the following: $(".myCssClass")[0].parentNode <li><span class="myCssClass">some text</span></li> I am attempting to add a CSS class to the parent span tag within the <li> element ...

Is there a way to load jQuery after the page has loaded? Any suggestions on how

Exploring jQuery $(document).ready(function(){ $('.categories').live('change', function() { var my_location = window.location.pathname.replace('admin/', ''); $(this).parents("tr").next("tr.subcat ...

Tips for smoothly animating and showing content as the user scrolls to a specific element on the page

Here is a sample template: <template> <div id="Test"> <transition name="fade"> <div class="row" id="RowOne"> <p>Lorem ipsum dolor odit qui sit?</p> </div> ...

Exploring Angular 4: Iterating Over Observables to Fetch Data into a Fresh Array

Context Currently, I am in the process of developing a find feature for a chat application. In this setup, each set of messages is identified by an index. The goal of the `find()` function is to retrieve each message collection reference from the `message ...

a function that repeats every single second

A challenge I am facing is creating a countdown timer with a time that refreshes every second. My current implementation uses setInterval, but it only seems to run once instead of every second. Can anyone help me identify the issue in my code? var countDo ...

Add different input strings to an array within the scope when there is a change in the input value (AngularJS)

My goal is to populate an empty array within the scope with strings. The number of elements in this array can vary depending on what the user types in the player count input field. $scope.playerNames = []; To achieve this, I am using a $watch function th ...

Ways to retrieve information when text is modified and a dropdown is selected within an input field

I have an input field with a text box and a dropdown. My goal is to trigger data based on text changes in one method, while using another method for the dropdown. Check out the code below. const allList = [ { id: "1", value: "Fruits" ...

How can I create an HTML select dropdown menu with a maximum height of 100% and a dynamic size?

The dropdown menu I created using an HTML select tag contains a total of 152 options. However, the large number of options causes some of them to be out of view on most monitors when the size is set to 152. I attempted to limit the number of displayed opti ...

Having trouble displaying an image in p5.js on Visual Studio Code

I can't seem to figure out how to load images in visual studio code for p5.js. Can someone help me understand the process of loading images in p5.js? I've set up a new project, but the images I try to load are not displaying correctly. How can I ...

Performing AJAX request when a link is clicked within a Wordpress website

I am looking for a way to initiate a PHP function in my Wordpress site when a link is clicked, rather than using a form submission. I have tried using an AJAX request but it doesn't seem to be working. Any suggestions would be greatly appreciated. Be ...

Is it possible for a UIViewImage to display its image beyond its boundaries?

While developing a photo viewer app, I encountered an issue where the image in our UIImageView controller was being drawn outside of its frame when the content mode was neither ScaleToFill nor Aspect Fit. To investigate further, I created a new project wi ...

Customizing Magnific Popup: Changing showCloseBtn and closeOnBgClick settings during display

Is there a way to customize the behavior of an open instance of a magnific popup? I want to have different settings for when the popup is closable and when it should be prevented from closing. It appears that these options are only available during initial ...

Enhancing website security using Content Security Policy in conjunction with Google Closure

Implementing CSP for my web application is a top priority. Here's the policy I have in mind: "default-src 'self' gap: cdvfile;" I rely on google closure for my javascript needs. However, it seems that without javascript optimization, my ...

What is the best way to ensure the initial item in an accordion group remains open by default when using NextJS?

I've successfully developed an accordion feature in NextJS from scratch and it's functioning flawlessly. However, I am looking to have the first item of the accordion open automatically when the page loads. Can anyone guide me on how to make this ...

Ways to verify if the inner <div> contains any text

I am attempting to determine if the inner <div> contains the text "Ended" and then remove it if it does. There are multiple <div> elements with the same class. I have attempted to use the .filter() method. My goal is to remove the container_one ...

Performing two consecutive nested AJAX requests in jQuery using JavaScript

I am facing an issue with my code. My goal is to create a cryptocurrency ranking feature on my website. I have integrated an API that provides logos, symbols, indices, prices, etc. of cryptocurrencies. However, I encountered a problem as this API doesn&apo ...

Error: The identifier has already been declared and cannot be re-declared

I am attempting to create a modal-cookie feature that will display a modal on page load if a cookie named "name" does not exist. However, I encountered an error: Uncaught SyntaxError: Identifier 'addCookie' has already been declared. This erro ...

Passing resolved data from a parent state to a nested view in Angular UI Router

Currently, I am developing an Angular web application that will showcase various financial events for the user. These events are categorized under a single ID and grouped into different categories. Each group needs to have its own HTML <table> for di ...