Reputation: 12388
I've been working with javascript and did something like this
var div = document.getElementById("bob");
div.addEventListener("click", function(){alert('foo');});
// all tests fail
//div.click();
//div.onclick();
//div.onClick();
var div2 = document.getElementById("adam");
// works
//div2.onclick();
var div3 = document.getElementById("iris");
div3.onclick = function(){alert('wat');};
// works
//div3.onclick();
//How do I trigger the div (the first div, "bob") "click" event?
code is here: http://jsfiddle.net/TVrfF/ , uncomment to test cases
So how can I trigger a click event setup via addEventListener (e.g. div "bob") with dojo or plain javascript?
Also, should I abandon using addEventListener from now on and just use element.onclick = function(){} due to this problem I'm having? What are the advantages of addEventListener?
Upvotes: 2
Views: 6650
Reputation: 8162
Is there a reason you need to call your function by simulating a click as opposed to just calling the function directly?
var fnDoWork = function() {
alert('do work');
}
var div = document.getElementById("bob");
dojo.connect(div, "onclick", fnDoWork);
// some other code
fnDoWork();
What you do lose, is not having the event which gives you mouse coordinates of a click. Most of the time this shouldn't be a big deal. I have only ever needed these when working with SVG.
Upvotes: 0
Reputation: 27292
Try this:
div.dispatchEvent("click");
Documentation here:
https://developer.mozilla.org/en/DOM/element.dispatchEvent
Upvotes: 2