Gil
Gil

Reputation: 1804

How to fire a DOM event with YUI3

I've encountered an annoying issue while working on YUI.

I have a main area and a navigation block. The elements in the main area can be activated with a direct click or by clicking an element in the navigation block that triggers the appropriate element in the main area.

As it turns out, triggering a click event programmatically in YUI isn't as simple as I thought it might be. Looking at the documentation I found pleanty of information on how to attach and delegate events but not how to call one.

I found this question, but it deals with creating a new custom event and not calling an existing one.

All other similar questions are answered with using .simulate(), but this is actually not the best option for compatability reasons and it's also not recommended by YAHOO itself for client-side use http://yuilibrary.com/yui/docs/event/simulate.html#faking. EDIT: After re-reading the section I realized the warning is irrelevant for the subject of this question.

I found a solution by calling the click() command in the node's DOM element, but this is really a last resort and I would like to know if there's a more "clean" way to do it through YUI.

Here is an example of what I'm doing now: http://jsfiddle.net/3fso2dg8/

In the example, the second button is triggering the click event of the first button by using the DOM element

Y.one('#clickme')._node.click();

CONCLUSIONS

After more fiddling with the code I came to realize simulate() is the preferred option in most cases, but not all.

The YUI vesrion I'm required to work with (3.14) has a known issue on simulating a click event in IE9 and above. Since - for other technical reasons - I cannot upgrade to whatever version this issue was fixed and I need to keep a multi-platform compatibility, my original solution is still the best option. Anyone else that uses YUI components that don't respond well on IE, maybe you stumbled upon the same issue so this is one way to solve it.

Upvotes: 2

Views: 489

Answers (1)

nettutvikler
nettutvikler

Reputation: 604

After looking for exactly the same functionality I just used simulate in user-facing code - where It would just mimic clicking with no return method etc. (simple submit button or choose fil trigger).

When I would needed "complex" functionality I would just add a class or new ID and add new delegate or "on" method in my code - following the: "If a function needs to respond to user action or be called programmatically, it should be written accordingly and called directly in the latter case." prinsipp.

So to summarize - I use simulate for very simple effects with no callbacks or other "advanced" stuff and (sadly) duplicate other delegate/on elements where simulating would be tricky...

Had also looked into your method (._node.click();) and I can't see no obvious difference comparing to simulate()...

Upvotes: 1

Related Questions