Event Observe and Event Listeners with Prototype


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

Series Navigation«Simple Hide and Show with PrototypeJavaScript Script.aculo.us Fade with a Timer»

Popularity: 55% [?]


Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!