1

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

2 Answers 2

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

you got it !

Sign up to request clarification or add additional context in comments.

1 Comment

$$(".message").invoke("hide")
1

a more succinct solution would be to use invoke:

$$('.elements').invoke('observe', 'click', yourfunction)

You can set this to run when the dom is ready by placing it within this code:

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

EDIT - this will fix your other issue:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.