Triggering the click event using dojo/javascript?

Go To StackoverFlow.com

2

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?

2012-04-04 22:24
by Derek
document.getElementById("iris").click() - binarious 2012-04-04 22:27


2

Try this:

div.dispatchEvent("click");

Documentation here:

https://developer.mozilla.org/en/DOM/element.dispatchEvent

2012-04-04 22:35
by Ethan Brown
will this work for IE, Chrome, and other major browsers - Derek 2012-04-04 22:36
in IE<9 use fireEvent: http://msdn.microsoft.com/en-us/library/ie/ms536423%28v=vs.85%29.asp - Dr.Molle 2012-04-04 22:37
I spoke too soon...this approach only works for custom events, and an Event object must be passed in, not an event name - Ethan Brown 2012-04-04 22:45


0

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.

2012-04-05 10:58
by Craig Swing
Ads