Search code examples
javascriptonclickprototypejsdom-events

Add onclick event on various elements on the basic of CSS class


I have various elements on a single page. They share a single class. I want to add a onclick event on all those elements using prototype.

For id I can do something like this:

Event.observe(window, 'load',
   function() {
$('id_of_the_element').addEventListener('onclick',any_function,true);
  }
);

This is good if we have id of the element. I want to do the same using CSS class, cause all the element share same class.

Update:

document.observe("dom:loaded", function() {
   $$('.message').invoke('observe', 'click', hide_all_messages)
});

function hide_all_messages()
{
$$('.message').hide();
}

This is not working.

error:

hide is not a function


Solution

  • $$('.myClass').each(
      function(element){
        Event.observe("click",element,any_function);
    }
    );
    

    you got it !