1

Possible Duplicate:
In Jquery, how can I tell between a programatic and user click?

Depending on the browser, there are several methods by which a link can be "clicked" using javascript.

IE (pre IE9)

element.click(); element.fireEvent('click');

Other browsers use:

element.dispatchEvent(evt) where evt is a mouseclick event.

I want to make sure that actual end user action was the originator of the event on particular links. The technique I use now is to override these methods and filter out click events, but it is easily defeated by reverting the methods back to the prototype versions before using them.

Is there any reliable, cross browser way to determine whether or not a click event is firing as a result of direct user action (they actually clicked the element).

Community
  • 1
  • 1
Joe Enzminger
  • 11,110
  • 3
  • 50
  • 75
  • You could hook into the mousedown and mouseup events also, and the other device specific events (like keypress). – Matt Whipple Sep 14 '12 at 17:50
  • I believe those can also be dispatched from javascript, correct? – Joe Enzminger Sep 14 '12 at 17:50
  • 1
    http://stackoverflow.com/questions/6674669/in-jquery-how-can-i-tell-between-a-programatic-and-user-click. Though keep in mind that if you want your site to be accessible and therefore accomodate different input devices this will get increasingly complicated. – Matt Whipple Sep 14 '12 at 17:53
  • This question was closed as duplicate, but the other question is specific to jQuery, and the answers posted are limited to jQuery functionality. I've posted additional information in the linked question that is relevant to both questions. – Joe Enzminger Sep 15 '12 at 16:54

1 Answers1

2

In Chrome, Firefox and Opera you can use Event.detail property, if it is not predefined by initUIEvent().

element.addEventListener('click', clickHandler, false);
function clickHandler (e) {
    if(e.detail > 0) {
        /* 1 = user click */
    } else {
        /* 0 = JS click */
    }
    return;
}

Unfortenately e.detail returns 1 in both cases in IE9 (and won't work at all in older IEs). It seems, that event properties are all exactly the same in IE (IE<9 including, 10 I don't know), despite of the source of the the click event.

Teemu
  • 22,918
  • 7
  • 53
  • 106