Friday, September 7th, 2007

Ajaxian Featured Tutorial: Extending DOM elements Prototype’s

Category: Prototype

The Prototype framework continues to be a popular solution for client-side development and with the renewed development efforts by the Prototype team, looks stronger than ever.

In this example-oriented tutorial, Juriy Zaytsev, who authored the very popular Context Menu plugin for Prototype, discusses how to use Element.addMethods method of Prototype to extend DOM elements with custom methods and allow chaining:

As an example, here’s a little helper, that I use quite often to display notifications (usually when form verification fails). We will update element with content, make it appear, wait couple of seconds and fade it out.

Note: The following example uses prototype version 1.6.0_rc0 and requires Scriptaculous’ effects module:


Element.addMethods({
flash: function(element, content) {
element = $(element);
new Effect.Appear(element, {
beforeStart: function() {
element.update(content);
},
afterFinish: function() {
Effect.Appear(element, {to: 0, delay: 3,
afterFinish: function(){
element.hide().setOpacity(1);
}})
}
})
return element;
}
})

Now we can simply do:

$(‘errorBox’).flash(‘login field should not be empty’);

The full tutorial can be found here.

Posted by Rey Bango at 8:46 am
2 Comments

++---
2.5 rating from 44 votes

2 Comments »

Comments feed TrackBack URI

Nice!!! Very cool post. :P

Comment by jdalton — September 7, 2007

First the global namespace was polluted, now the DOM. Yuck.

Comment by David — September 8, 2007

Leave a comment

You must be logged in to post a comment.