Question

Jquery has a great language construct that looks like this:

$(document).ready(function() {
    $("a").click(function() {
        alert("Hello world!");
    });
});

As you might guess this, once the document has loaded, binds a custom function to the onClick event of all a tags.

The question is, how can I achieve this same kind of behavior in Prototype?

Was it helpful?

Solution

Prototype 1.6 provides the "dom:loaded" event on document:

document.observe("dom:loaded", function() {
    $$('a').each(function(elem) {
        elem.observe("click", function() { alert("Hello World"); });
    });
});

I also use the each iterator on the array returned by $$().

OTHER TIPS

$(document).observe('dom:loaded', function() {
    $$('a').invoke('observe', 'click', function() {
        alert('Hello world!');
    });
});
Event.observe(window, 'load', function() { 
     Event.observe(element, 'click', function() { 
         alert("Hello World!");
     });
});

Of course you need to "select" the elements first in Prototype.

This article gives a pretty good overview of Prototype's event library. I think, compared to jQuery, this is a stone age api. :)

http://alternateidea.com/blog/articles/2006/2/8/working-with-events-in-prototype

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top