Prototype - click event by element class name

18,056

Solution 1

Unlike jQuery, handing selectors with multiple results in Prototype works a little differently. You need to handle each selected result separately using .each().

$$('.btn').each(function(element) {
    element.observe('click', respond);
})

This is one of the reasons I moved over to jQuery. The other reason: knowing jQuery is marketable and knowing Prototype is not.

Solution 2

Can be also be done with a single-liner, as someone already suggested in a comment:

$$('.btn').invoke('observe', 'click', respond);
Share:
18,056
David
Author by

David

Updated on June 14, 2022

Comments

  • David
    David about 2 years

    I am new to the prototype framework and am trying something really simple and failing. I am trying to respond to a click event on a button like so:

    $$('.btn').observe('click', respond);
    function respond(event) {
        alert("hello");
    }
    

    Why isn't this working? Please help!

  • David
    David over 13 years
    Thats just stupid. Thanks. I am from a jquery background and am being forced to use prototype for an upcomming project - from what i have seen it is miles behind jquery with regards to dom manipulation
  • David
    David over 13 years
    Also - this is not mentioned in the documentation from what I can see!
  • Diodeus - James MacFarlane
    Diodeus - James MacFarlane over 13 years
    I wouldn't say it's miles behind. It can do all of the same things, but not in such a concise manner as jQuery. I worked with it before jQuery came onto the market. Back then it was by far the best choice. But, yeah, doing things with jQuery is sooo much easier.
  • Diodeus - James MacFarlane
    Diodeus - James MacFarlane over 13 years
    You can also do the same thing by using "invoke". api.prototypejs.org/language/enumerable/prototype/invoke
  • Justin
    Justin about 13 years
    Ah, thank you! Struggled with how to do this for too long (I too come from jQuery). Ironic that the JS library for the framework designed to be elegant is far less elegant than jQuery.
  • Diodeus - James MacFarlane
    Diodeus - James MacFarlane about 13 years
    Well Prototype was out earlier, so jQuery had a lot to base itself upon.