Wednesday, February 9, 2011

Binding custom functions to DOM events in prototype?

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?

  • 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

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

    Can you elaborate on "selecting the elements first"?

    Can I do this?

    Event.observe($$('a'), 'click', function(){
      alert('Hello World!');
    });
    
    From Mark Biek
  • 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...

    From Mark Biek
  • 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 $$().

    Erlend Halvorsen : Nice :) Seems Prototype has learned some new tricks since I last used it!
    From erlando
  • $(document).observe('dom:loaded', function() {
        $$('a').invoke('observe', 'click', function() {
            alert('Hello world!');
        });
    });
    
    seengee : this would be my solution also
  • @Mark Biek

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

0 comments:

Post a Comment