Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prototype - click event by element class name

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!

like image 786
David Avatar asked Oct 15 '10 19:10

David


2 Answers

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

$$('.btn').invoke('observe', 'click', respond);
like image 52
acme Avatar answered Oct 27 '22 19:10

acme


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.

like image 36
Diodeus - James MacFarlane Avatar answered Oct 27 '22 19:10

Diodeus - James MacFarlane