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);
Author by
David
Updated on June 14, 2022Comments
-
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 over 13 yearsThats 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 over 13 yearsAlso - this is not mentioned in the documentation from what I can see!
-
Diodeus - James MacFarlane over 13 yearsI 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 over 13 yearsYou can also do the same thing by using "invoke". api.prototypejs.org/language/enumerable/prototype/invoke
-
Justin about 13 yearsAh, 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 about 13 yearsWell Prototype was out earlier, so jQuery had a lot to base itself upon.