Search code examples
javascriptjqueryyui

Translating jquery idiom to YUI


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.


Solution

  • 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.