Alex Rivera | Logout

Fake "click" to activate an onclick method

Asked 2008-12-07T12:12:29.180
64

I have an element with an onclick method.

I would like to activate that method (or: fake a click on this element) within another function.

Is this possible?

Edit
Report

3 Answers

9
var clickEvent = new MouseEvent('click', {
  view: window,
  bubbles: true,
  cancelable: true
});
var element = document.getElementById('element-id'); 
var cancelled = !element.dispatchEvent(clickEvent);
if (cancelled) {
  // A handler called preventDefault.
  alert("cancelled");
} else {
  // None of the handlers called preventDefault.
  alert("not cancelled");
}

element.dispatchEvent is supported in all major browsers. The example above is based on an sample simulateClick() function on MDN.

answered 2008-12-07T12:34:28.230
3

This is a perfect example of where you should use a javascript library like Prototype or JQuery to abstract away the cross-browser differences.

answered 2008-12-07T12:38:54.790
1

I haven't used jQuery, but IIRC, the first method mentioned doesn't trigger the onclick handler.

I'd call the associated onclick method directly, if you're not using the event details.

answered 2008-12-07T12:27:26.560

Your Answer