Event Observe and Event Listeners with Prototype

by Terri Ann on December 15, 2007

This entry is part 2 of 10 in the series Prototype Tutorial

Event listeners are very important tools for embedding JavaScript in within the <body> or <head> of your document. They allow you to ensure the JavaScript is available only once the page loads entirely, or when a certain element loads, ensuring that your function never returns an error because it didn’t recognize that the element it is supposed to effect was on the page, it just hadn’t loaded yet.

The following snippet will hide the element with the id featurebox-1 when the window is loaded in entirety. If you didn’t use the Event.observe you’d have to use the $('featurebox-1').hide(); after the element in the document or use one of the following two methods:

Example 1 – Using the onload Attribute of the Body Tag

HTML/JavaScript

<script type="text/javascript">
function init() {
    $('featurebox-1').hide();
});
</script>
<body onload="init();">

Or

HTML/JavaScript

 <body onload="$('featurebox-1').hide();">

Using the following snippet you have the ability to move and change the code’s placement without any worries that moving items would effect the outcome.

Example 2 – JavaScript that can be Place Anywhere

JavaScript

<script type="text/javascript">
Event.observe(window, 'load', function() {
    $('featurebox-1').hide();
});
</script>

There is also a way to make Event.observe appear to listen for specific events, like clicking on a link, or a div or some other element.

In the following code example you’ll see that when an element with the id featurebox-1-listen is clicked it will hide the element with the id featurebox-1 but that this action will not be possible until the entire window has loaded; that will ensure all elements called within this function are fully loaded and ready to go before it can start to ‘listen’ for the click on featurebox-1-listen.

Example 3 – Javascript that can be Placed Anywhere, Including a click Listener

JavaScript

Event.observe(window, 'load', function() {
    Event.observe('featurebox-1-listen', 'click', function(){
        $('featurebox-1').hide();
    });
});

Summary

Prototype Functions Used

Prototype Functions Mentioned

{ 1 comment… read it below or add one }

1 Alexis July 10, 2009 at 5:19 pm

Hi I have to event.observe for all my input tags With JQuery I use ‘input’ and all tags of this kind will be affected but I donĀ“t know how to make it the same with prototype js. Is there a way to make an action for a group of tags?

Thanks for the answer.

Leave a Comment

Previous post:

Next post: