views:

135

answers:

2

How can I translate the following jquery idiom to YUI?

$("a").click(function(event){ alert("Saw a click!"); });

The above is supposed to add a custom on-click event to all anchor tags in the document.

+5  A: 

YUI 3

Y.all('li').on('click', function() {
        alert('Clickety-click!');
    });

YUI 2

var lis = document.getElementsByTagName("li");
YAHOO.util.Event.addListener(lis, 'click', function() {
        alert('Clickety-click!');
    });

Answers from: http://stackoverflow.com/questions/813523/translate-the-following-jquery-code-to-yui-2-x-code

Also: YUI 3 will support chaining operations, until then use the dedchain library from dechain.dustindiaz.com

nunb
Your YUI2 example can be smaller if you remove the intermediate "lis" variable.
Tivac
+1  A: 

Better to use event delegation

YUI 3*

Y.delegate('click', function (e) {
    alert("Click received");
}, document, 'a');

or

Y.get(document).delegate('click',fn, 'a');

YUI 2

YAHOO.util.Event.on(document,'click',function (e) {
    var target = YAHOO.util.Event.getTarget(e);
    if (target.nodeName && target.nodeName.toLowerCase() === 'a') {
        alert("Click received");
    }
});
  • the YUI 3 beta release has a bug in delegate that prevents document listeners from working. This is fixed for the upcoming GA release.
Luke