4

I have event listener myObject.addEventListener('click',this.doSomething,false) on element. It works fine when I do mouse click but I cannot figure out how to trigger click from JavaScript. It seems like element.click() does not work for divs?

I am using jQuery and I have also tried trigger('click') but nothing is happening.

How can I in JavaScript execute the EventListener?

Update:

Here is sample code http://jsbin.com/iniwi5/2

jpkeisala
  • 8,566
  • 7
  • 30
  • 39
  • There are tons of exact duplicates, e.g. [how can I trigger a JavaScript event click](http://stackoverflow.com/questions/2381572/how-can-i-trigger-a-javascript-event-click), [JavaScript: Invoking click-event of an anchor tag from javascript](http://stackoverflow.com/questions/980709/javascript-invoking-click-event-of-an-anchor-tag-from-javascript), etc. – maerics Jun 23 '11 at 20:24
  • Neither of those "duplicates" are formulated with event listeners in mind. – zjmiller Jun 23 '11 at 20:59
  • Yes, this is specific for Event Listener, if I was using normal jQuery .click() listener the code works just fine but seems like addEventListener behaves differently. – jpkeisala Jun 26 '11 at 09:38

3 Answers3

5

Can you bind the event using jQuery instead?

$(myobject).click(function() {

});

Then

myobject.trigger('click');

would programmatically trigger the click.

andyb
  • 43,435
  • 12
  • 121
  • 150
  • 'click'ing a div is basically a custom event which you can't do natively. So I agree - this is the easiest way to do it. – Adam A Jun 23 '11 at 21:45
  • I agree this as workaround, I could not figure out to make this with Event Listeners so I refactor my code to use .click() – jpkeisala Jun 26 '11 at 09:40
0

To trigger a click event listener added via addEventListener, you need to manually dispatch a click event, using either dispatchEvent (for standards-compliant browsers) or fireEvent (for IE < 9).

John
  • 29,546
  • 11
  • 78
  • 79
-1

Try this:

myObject.click; // no `()`

OR:

(myObject.click)();
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • `myObject.click` is wrong -- if click exists at all, it's a function. The second example is the same as `myObject.click()`, which is only standardized for [INPUT elements of certain types](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-2651361). You can't rely on arbitrary elements to support it. – John May 10 '12 at 19:17