Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to intercept/override all click events in the page?

I've written an html5 application which is supposed to work on mobile devices. 90% of the time it works fine however in certain devices (mostly androids 4.0+) the click events fire twice.

I know why that happens, I'm using iScroll 4 to simulate native scrolling and it handles the events that happen inside the scroll.(line 533 dispatches the event if you're interested) Most of the time it works fine but in certain devices both the iScroll dispatched event and the original onClick event attached to the element are fired, so the click happens twice. I can't find a pattern on which devices this happen so I'm looking for alternatives to prevent double clicks.

I already came up with an ugly fix that solves the problem. I've wrapped all the clicks in a "handleClick" method, that is not allowed to run more often than 200ms. That became really tough to maintain. If I have dynamically generated content it becomes a huge mess and it gets worse when I try to pass objects as parameters.

var preventClick = false;

function handleClick(myFunction){

   if (preventClick)
      return;
   setTimeout(function(){preventClick = true;},200);

   myFunction.call():
}

 function myFunction(){

  ...

 }

<div onclick='handleClick(myfunction)'> click me </div>

I've been trying to find a way to intercept all click events in the whole page, and there somehow work out if the event should be fired or not. Is it possible to do something like that?

Set myFunction on click but before it's called, trigger handleClick()? I'm playing with custom events at the moment, it's looking promising but I'd like to not have to change every event in the whole application.

<div onclick='myfunction()'> click me </div>
like image 243
caiocpricci2 Avatar asked Oct 18 '13 12:10

caiocpricci2


1 Answers

You can do that with the following ( i wouldn't recommend it though):

$('body').on('click', function(event){
  event.preventDefault();
  // your code to handle the clicks
});

This will prevent the default functionality of clicks in your browser, if you want to know the target of the click just use event.target. Refer to this answer for an idea on how to add a click check before the preventDefault();

like image 127
Patsy Issa Avatar answered Nov 12 '22 10:11

Patsy Issa