3

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?

Rob W
  • 315,396
  • 71
  • 752
  • 644
Mark Biek
  • 135,050
  • 52
  • 150
  • 195

3 Answers3

8

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 $$().

erlando
  • 6,588
  • 4
  • 20
  • 29
4
$(document).observe('dom:loaded', function() {
    $$('a').invoke('observe', 'click', function() {
        alert('Hello world!');
    });
});
eyelidlessness
  • 58,600
  • 11
  • 86
  • 93
1
Event.observe(window, 'load', function() { 
     Event.observe(element, 'click', function() { 
         alert("Hello World!");
     });
});

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

David McLaughlin
  • 4,858
  • 3
  • 29
  • 34
  • Can you elaborate on "selecting the elements first"? Can I do this? `Event.observe($$('a'), 'click', function(){ alert('Hello World!'); });` – Mark Biek Sep 08 '08 at 12:56
  • @Mark Biek `Event.on(document, 'click', 'a.greeter_class[rel]', function(event, elt) { alert("Hello " + elt.readAttribute('rel')); event.stop(); });` – Alex Bartlow Jul 15 '10 at 16:42
  • FYI this is Prototype 1.7 syntax which is still in beta – robjmills Jul 16 '10 at 10:28