Javascript: simulate a click on a link

danny picture danny · Mar 16, 2009 · Viewed 13.8k times · Source

I have a link that has a listener attached to it (I'm using YUI):

YAHOO.util.Event.on(Element, 'click', function(){ /* some functionality */});

I would like to the same functionality to happen in another scenario that doesn't involve a user-click. Ideally I could just simulate "clicking" on the Element and have the functionality automatically fire. How could I do this? Too bad this doesn't work:

$('Element').click()

Thanks.

Answer

Eli Grey picture Eli Grey · Mar 16, 2009

MDC has a good example of using dispatchEvent to simulate click events.

Here is some code to simulate a click on an element that also checks if something canceled the event:

function simulateClick(elm) {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var canceled = !elm.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    // uh-oh, did some XSS hack your site?
  } else {
    // None of the handlers called preventDefault
    // do stuff
  }
}