Prototype.js: The Magic of the $() Function and AJAX
In 2005, web development is in a state of chaos. We're trying to build "Web 2.0" applications, but the browsers (IE6 and Firefox 1.0) are vastly different. We're tired of writing document.getElementById() and fighting with XMLHttpRequest.
Then came Prototype.js. Created by Sam Stephenson as part of the Ruby on Rails framework, it's now a standalone library that is fundamentally changing how we write JavaScript.
The $() Function
The most iconic feature of Prototype is the $() function. It's not just a shortcut for getElementById; it also "extends" the returned DOM element with new, useful methods.
// Old way
var myDiv = document.getElementById('myElement');
myDiv.style.display = 'none';
// Prototype way
$('myElement').hide();
$('myElement').addClassName('active');
$('myElement').update('Hello, World!');
Classes and Inheritance
JavaScript's prototypal inheritance is confusing for many developers coming from Java or Ruby. Prototype.js provides a clean Class.create() syntax.
var Animal = Class.create({
initialize: function(name) {
this.name = name;
},
eat: function() {
alert(this.name + " is eating.");
}
});
var Dog = Class.create(Animal, {
bark: function() {
alert(this.name + " says: Woof!");
}
});
var fido = new Dog("Fido");
fido.eat();
fido.bark();
The AJAX Object
Before Prototype, writing an AJAX request was a 20-line nightmare involving activeX controls for IE. Prototype wraps this in a beautiful Ajax.Request object.
new Ajax.Request('/get_data.php', {
method: 'get',
parameters: { id: 123 },
onSuccess: function(response) {
var json = response.responseText.evalJSON();
$('result_area').update(json.message);
},
onFailure: function() {
alert('Something went wrong...');
}
});
Prototype.js isn't just a library; it's a philosophy. It extends the built-in JavaScript objects (like Array and String) with methods from Ruby, making the language feel more modern and expressive. While some complain about "polluting the global namespace," we developers are just happy that coding for the web finally feels like fun.
Aunimeda builds modern web frontends - from single-page applications to complex multi-locale sites.
Contact us to discuss your frontend project. See also: Web Development, Corporate Website Development