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
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./iniwi5/2
Share Improve this question edited Jun 23, 2011 at 20:40 jpkeisala asked Jun 23, 2011 at 20:22 jpkeisalajpkeisala 8,9668 gold badges32 silver badges40 bronze badges 3- There are tons of exact duplicates, e.g. how can I trigger a JavaScript event click, JavaScript: Invoking click-event of an anchor tag from javascript, etc. – maerics Commented Jun 23, 2011 at 20:24
- Neither of those "duplicates" are formulated with event listeners in mind. – zjmiller Commented Jun 23, 2011 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 Commented Jun 26, 2011 at 9:38
3 Answers
Reset to default 5Can you bind the event using jQuery instead?
$(myobject).click(function() {
});
Then
myobject.trigger('click');
would programmatically trigger the click.
To trigger a click event listener added via addEventListener
, you need to manually dispatch a click event, using either dispatchEvent
(for standards-pliant browsers) or fireEvent
(for IE < 9).
Try this:
myObject.click; // no `()`
OR:
(myObject.click)();