Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event.observe function - observe element by class instead of id

There is prototype js function:

Event.observe(element, eventName, handler)

here the element means element's ID.

Is it possible to put here element's class?

I got this element from third party with class attribute only.

like image 249
sergionni Avatar asked Feb 05 '10 10:02

sergionni


1 Answers

$$ can retrieve elements by css selector, including by class via the period notation .:

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

To answer your question, Event.observe is the "static" version of observe (for all intents and purposes). As a convenience Prototype automagically makes .observe available off of all DOM elements (fetched with either $ 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);
like image 187
Roatin Marth Avatar answered Sep 19 '22 12:09

Roatin Marth