Event.observe function - watch an element for a class instead of id

There is a prototype of the js function:

Event.observe (element, eventName, handler)

here element means the identifier of the item.

Can a class element be placed here?

I received this element from a third party only with a class attribute.

+6
javascript prototypejs event-handling class
source share
1 answer

$$ can extract elements using the css selector, including by class through a period designator . :

 $$('.myClass'); // array with all elements that have class "myClass" 

To answer your question, Event.observe is a "static" version of observe (for all purposes and tasks). As a convenience, Prototype automatically makes .observe available for all DOM elements (selected using $ or $$ ):

Examples:

 // get one item by id with $ and attach an event listener: $('myId').observe(eventName, handler); // get many items by class with $$ and attach an event listener: $$('.myClass').each(function(element) { element.observe(eventName, handler); }); // or shorter: $$('.myClass').invoke('observe', eventName, handler); 
+22
source share

All Articles