The script.aculo.us library
Delving into the JavaScript frameworks, we would like to present the essence of script.aculo.us library.
As we mentioned in JS Frameworks introduction, Prototype JS and script.aculo.us libraries are often seen together.
The library, which now referred to, is like an extension of Prototype JS of visual effects, animation, Drag and Drop, creating widgets, tools for working with DOM, or Ajax controls. Functions of this library are easy to use, and of course there are cross-browser.
Working with script.aculo.us library
At the beginning we add Prototype JS and script.aculo.us to the document. Let’s start with a few words about how to create dynamic elements.
Component that supports the creation of DOM elements is the Builder, fulfilling the function of pattern.
Example — using the Builder component:
var tbl = Builder.node("tbl",
{ border: 0, width: 200 },
[ Builder.node( "tr", [
Builder.node("td", {width: 100}, "column 1" ),
Builder.node("td", {width: 100}, "column 2" ),
Builder.node("td", {width: 100}, "column 3" )
])
]);
$('mydiv').appendChild(tbl);
Example #2:
var element = Builder.node('div', { id: 'ghosttrain' }, [
Builder.node('div',
{ className: 'controls', style: 'font-size:11px;' },
[
Builder.node('h1', 'Ghost Train'),
'testtext', 2, 3, 4,
Builder.node('ul', [
Builder.node('li', { className: 'active',
onclick: 'test()' }, 'Record')
]),
]),
]);
Drag&drop support
Script.aculo.us allows us to quickly implement Drag and Drop, and add eye-catching animations.
The library provides for this purpose following classes:
– Draggable — defines an object that we will drag,
– Droppables — allows to design an appropriate response for dropping the item.
The Draggable class
That means elements, which can be dragged.
Example — Draggeble test:
var test = Builder.build("<span>Displacement</span>");
document.getElementsByTagName("body")[0].appendChild(test);
new Draggable(test);
new Draggable('id_of_element', [options]);
More details about this class you can find here.
Example #2 — Draggable — settings:
new Draggable('mydiv', { constraint: 'horizontal',
handle: 'handle' });
var mydrag = new Draggable('dv1', { revert: true });
mydrag.destroy();
// assignment back
// new Draggable('dd1', { revert: true });
new Draggable('dd1', { revert: true, snap: [40, 40] });
new Draggable('dd2', { scroll: window });
The Droppables class
So elements that can be dropped.
Example — using Droppables:
Droppables.add('id_of_element',[options]);
Droppables.add('shopping_cart', {
accept: 'products',
onDrop: function(element) {
$('shopping_cart_text').
update('Dropped the ' + element.alt + ' on me.');
}
});
Droppables.remove(element); // removing
Example — all the elements of the list as Draggable:
$$('container li').each( function(li) {
new Draggable(li);
});
And now we can drag items of the list.