Jim
Jim

Reputation: 11

Handling events using Prototype

So I have the small code snippet below, which I would ideally like to call the function to alert me with hello when the #results_more element is clicked...

$('results_more').observe('click', function(evt) {
   alert('hello');
});

However, I think I'm doing something terribly wrong if something this easy doesn't work. Anything I may be overlooking with the Prototype library, or Javascript in general?

Upvotes: 1

Views: 67

Answers (1)

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94284

At face value, there shouldn't be anything wrong with your code, but you aren't giving enough information.

  • Does exactly one element with id="results_more" exist? What is the result if you alert($('results_more'))?
  • Has the element been created already at the point you are trying to register the event listener? You cannot register events on (or for that matter collect) elements that have not yet been added to the DOM. You can get around this by moving your code to after the element is created in your HTML or put it within a dom:loaded event listener.

Take a look at jsfiddle.net/zDa7m for a simple example.

Upvotes: 1

Related Questions