tags:

views:

2095

answers:

5

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.

+4  A: 

You can declare your function separately.

function DoThisOnClick () {
}

Then assign it to onclick event as you do right now, e.g.:

YAHOO.util.Event.on(Element, 'click', DoThisOnClick)

And you can call it whenever you want :-)

DoThisOnClick ()
Ilya Birman
True... but the YUI Event handler has access to variables such as 'this' and other parameters handled by the YUI framework. It would be ideal to just fire the same event.
"this" holds reference to the object which you clicked. If you call the function yourself, there’s no such object. So your function needs to deal with it. Try: if (this) // do smth; else // do smth when there’s no “this”
Ilya Birman
A: 

Of course $('Element').click() won't work, but it can if you include jquery, it works well alongside yui.

As I untestand you need to do the following:

function myfunc(){
//functionality
}

YAHOO.util.Event.on(Element, 'click', myfunc);

Then call myfunc when something else needs to happen.

Vasil
A: 

The inability to simulate a user-click on an arbitrary element is intentional, and for obvious reasons.

wombleton
+5  A: 

You're looking for fireEvent (IE) and dispatchEvent (others).

For YUI 3 this is all wrapped up nicely in Y.Event.simulate():

YUI().use("node", function(Y) {
    Y.Event.simulate(document.body, "click", { shiftKey: true })
})
Crescent Fresh
+3  A: 

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
  }
}
Eli Grey
This works very well, and it's very easy to implement. Thanks !
gramm