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?

1
  • 1
    document.getElementById("iris").click() ? Commented Apr 4, 2012 at 22:27

2 Answers 2

2

Try this:

div.dispatchEvent("click");

Documentation here:

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

Sign up to request clarification or add additional context in comments.

2 Comments

I spoke too soon...this approach only works for custom events, and an Event object must be passed in, not an event name.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.