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
  • 341,306
  • 83
  • 791
  • 678
Mark Biek
  • 146,731
  • 54
  • 156
  • 201

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

Michael M.
  • 10,486
  • 9
  • 18
  • 34
erlando
  • 6,736
  • 4
  • 24
  • 29
4
$(document).observe('dom:loaded', function() {
    $$('a').invoke('observe', 'click', function() {
        alert('Hello world!');
    });
});
eyelidlessness
  • 62,413
  • 11
  • 90
  • 94
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
  • 5,108
  • 4
  • 34
  • 35
  • 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