views:

1922

answers:

7

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?

+1  A: 
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
+1  A: 

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

Erlend Halvorsen
That's because the linked article is two years old. The API has evolved quite a bit since then. ;-)
savetheclocktower
A: 

@David

Can you elaborate on "selecting the elements first"?

Can I do this?

Event.observe($$('a'), 'click', function(){
  alert('Hello World!');
});
Mark Biek
A: 

Eriend

I, so far, prefer a lot of things about Jquery as well. But I have a large Prototype code-base to work with. When in Rome...

Mark Biek
+6  A: 

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
Nice :) Seems Prototype has learned some new tricks since I last used it!
Erlend Halvorsen
+3  A: 
$(document).observe('dom:loaded', function() {
    $$('a').invoke('observe', 'click', function() {
        alert('Hello world!');
    });
});
eyelidlessness
this would be my solution also
seengee
A: 

@Mark Biek

Event.on(document, 'click', 'a.greeter_class[rel]', function(event, elt) {
  alert("Hello " + elt.readAttribute('rel')); event.stop();
});
Alex Bartlow
FYI this is Prototype 1.7 syntax which is still in beta
seengee