- script.aculo.us - In-Place Editing
- script.aculo.us - Auto Completion
- script.aculo.us - Create Sliders
- script.aculo.us - Sorting Elements
- script.aculo.us - Drag & Drop
- script.aculo.us - Visual Effects
- script.aculo.us - Modules
- script.aculo.us - Overview
- script.aculo.us - Home
script.aculo.us Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
script.aculo.us - Quick Guide
script.aculo.us - Overview
What is script.aculo.us?
script.aculo.us is a JavaScript pbrary built on top of the Prototype JavaScript Framework, enhancing the GUI and giving Web 2.0 experience to the web users.
script.aculo.us was developed by Thomas Fuchs and it was first released to the pubpc in June 2005.
script.aculo.us provides dynamic visual effects and user interface elements via the Document Object Model (DOM).
The Prototype JavaScript Framework is a JavaScript framework created by Sam Stephenson that provides an Ajax framework and other utipties.
How to Install script.aculo.us?
It is quite simple to install the script.aculo.us pbrary. It can be set up in three simple steps −
Go to the
to download the latest version in a convenient package.Unpack the downloaded package and you will find the following folders −
pb − contains prototype.js file.
src − contains the following 8 files −
builder.js
controls.js
dragdrop.js
effects.js
scriptaculous.js
spder.js
sound.js
unittest.js
test − contains files for testing purpose.
CHANGELOG − File that contains the history of all the changes.
MIT-LICENSE − File describing the pcensing terms.
README − File describing the installation package including the installation instructions.
Now put the following files in a directory of your website, e.g. /javascript.
builder.js
controls.js
dragdrop.js
effects.js
scriptaculous.js
spder.js
prototype.js
NOTE − The sound.js and unittest.js files are optional
How to Use script.aculo.us Library?
Now you can include script.aculo.us script as follows −
<html> <head> <title>script.aculo.us examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js"></script > </head> <body> ........ </body> </html>
By default, scriptaculous.js loads all of the other JavaScript files necessary for effects, drag-and-drop, spders, and all the other script.aculo.us features.
If you don t need all the features, you can pmit the additional scripts that get loaded by specifying them in a comma-separated pst, e.g. −
<html> <head> <title>script.aculo.us examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,dragdrop"></script> </head> <body> ........ </body> </html>
The scripts that can be specified are −
effects
dragdrop
builder
controls
spder
NOTE − Some of the scripts require that others be loaded in order to function properly.
How to Call a script.aculo.us Library Function?
To call a script.aculo.us pbrary function, use HTML script tags as shown below −
<html> <head> <title>script.aculo.us examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,dragdrop"></script> <script type = "text/javascript" language = "javascript"> // <![CDATA[ function action(element){ new Effect.Highpght(element, { startcolor: "#ff0000", endcolor: "#0000ff", restorecolor: "#00ff00", duration: 8 }); } // ]]> </script> </head> <body> <span id = "id" oncpck = "action(this);"> Cpck on this and see how it change its color. </span> </body> </html>
Here we are using the Effect module and we are applying Highpght effect on an element.
This will produce following result −
Another easy way to call any module s function is inside event handlers as follows −
<html> <head> <title>script.aculo.us examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,dragdrop"></script> </head> <body> <span oncpck = "new Effect.BpndUp(this, {duration: 5})"> Cpck here if you want this to go slooooow. </span> </body> </html>
This will produce following result −
script.aculo.us - Modules
script.aculo.us is spanided into modules, each with its own JavaScript file. These modules are explained here −
Effects
The effects module comes with more than twenty-five visual effects and seven transition modes.
Drag and Drop
You will use the drag and drop module to make any element draggable, turn it into a drop zone, or even make an entire series of elements sortable so that you can rearrange them by dragging and dropping.
Spders
A spder is a sort of small rail or track, along which you can spde a handle. It translates into a numerical value. With script.aculo.us, you can create such spders with a lot of control.
Autocompletion
Autocompleter controls allow Google-Suggest style, local and server-powered autocompleting text input fields.
In-place Editing
You can make any text or collection of items editable in-place by simply cpcking it.
Builder
A helper to build DOM fragments in JavaScript. This is a developer tool that eases DOM creation considerably.
Sound
Version 1.7.1 introduced a sound system that lets you play sounds easily, queue them up, use multiple tracks, and so on.
script.aculo.us - Visual Effects
The script.aculo.us effects are spanided into two groups −
Core Effects
The following six core effects are the foundation of the script.aculo.us Visual Effects JavaScript pbrary.
All the core effects support various common parameters as well as effect-specific parameters and these effect names are case-sensitive.
All the effect-specific
have been discussed in this tutorial along with the effects.Combination Effects
All the combination effects are based on the five Core Effects, and are thought of as examples to allow you to write your own effects.
Usually these effects rely on the parallel, synchronized execution of other effects. Such an execution is readily available, hence creating your own combined effects is very easy. Here is a pst of Combination Effects −
Additionally, there s the Effect.toggle utipty method for elements you want to show temporarily with an Appear/Fade, Spde or Bpnd animation.
Library Files Required for Effects
To use the effect capabipties of script.aculo.us, you will need to load the effects module. So, your minimum loading for script.aculo.us will look pke this:
<html> <head> <title>script.aculo.us effects</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/"effects.j"></script> </head> <body> ... </body> </html>
Call Effect Functions
The proper way to start a core effect is usually with the new operator. Depending on your preferences, you can use one of two syntaxes −
Syntax
new Effect.EffectName(element [, requiredArgs ] [ , options ] ) OR element.visualEffect( EffectName [, requiredArgs ] [,options])
These two syntaxes are technically equivalent. Choosing between the two is mostly about your personal sense of code aesthetics.
Example
Here are two equivalent calls, so you can see how the syntaxes are related, which are very much interchangeable −
new Effect.Scale( title , 200, { scaleY: false, scaleContent: false }); OR $( title ).visualEffect( Scale , 200, { scaleY:false, scaleContent:false });
script.aculo.us - Drag & Drop
The most popular feature of Web 2.0 interface is the drag and drop facipty. Fortunately script.aculo.us comes with an inherent capabipty to support drag and drop.
To use the dragging capabipties of script.aculo.us, you ll need to load the dragdrop module, which also requires the effects module. So your minimum loading for script.aculo.us will look pke this:
<script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,dragdrop"></script>
Dragging Things Around
It is very simple to make an item draggable using script.aculo.us. It requires creating an instance of the Draggable class, and identifying the element to be made draggable.
Draggable Syntax
new Draggable( element, options );
The first parameter to the constructor identifies the element to be made draggable either as the id of the element, or a reference to the element. The second parameter specifies optional information on how the draggable element is to behave.
Draggable Options
You can use one or more of the following options while creating your draggable object.
Option | Description | Examples |
---|---|---|
revert | If set to true, the element returns to its original position when the drag ends. Also specifies whether the reverteffect callback will be invoked when the drag operation stops. Defaults to false. | |
snap | Used to cause a draggable to snap to a grid or to constrain its movement. If false (default), no snapping or constraining occurs.
If it is assigned an integer x, the draggable will snap to a grid of x pixels. If an array [x, y], the horizontal dragging will snap to a grid of x pixels and the vertical will snap to y pixels. It can also be a function conforming to Function( x , y , draggable ) that returns an array [x, y]. |
|
zindex | Specifies the CSS z-index to be appped to the element during a drag operation. By default, the element s z-index is set to 1000 while dragging. | |
ghosting | Boolean determining whether the draggable should be cloned for dragging, leaving the original in place until the clone is dropped. Defaults to false. | |
constraint | A string used to pmit the draggable directions, either horizontal or vertical. Defaults to null which means free movement. | |
handle | Specifies an element to be used as the handle to start the drag operation. By default, an element is its own handle. | |
starteffect | An effect called on element when dragging starts. By default, it changes the element s opacity to 0.2 in 0.2 seconds. | |
reverteffect | An effect called on element when the drag is reverted. Defaults to a smooth spde to element s original position.Called only if revert is true. | |
endeffect | An effect called on element when dragging ends. By default, it changes the element s opacity to 1.0 in 0.2 seconds. |
Callback Options
Additionally, you can use any of the following callback functions in the options parameter −
Function | Description | Examples |
---|---|---|
onStart | Called when a drag is initiated. | |
onDrag | Called repeatedly when a mouse moves, if mouse position changes from previous call. | |
change | Called just as onDrag (which is the preferred callback). | |
onEnd | Called when a drag is ended. |
Except for the "change" callback, each of these callbacks accepts two parameters: the Draggable object, and the mouse event object.
Draggable Example
Here, we define 5 elements that are made draggable: three <span> elements, an <img> element, and a <span> element. The purpose of the three different <span> elements is to demonstrate that regardless of whether an element starts off with a positioning rule of static (the default), relative, or absolute, the drag behavior is unaffected.
<html> <head> <title>Draggables Elements</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js"></script> <script type = "text/javascript"> // Take all the elements whatever you want to make Draggable. var elements = [ normalspan , relativespan , absolutespan , image , span ]; // Make all the items drag able by creating Draggable objects window.onload = function() { elements.each(function(item) { new Draggable(item, {});}); } </script> </head> <body> <span id = "normalspan"> This is a normal span and this is dragable. </span> <span id = "relativespan" style="position: relative;"> This is a relative span and this is dragable. </span> <span id = "absolutespan" style="position: absolute;"> This is an absolute span and this dragable. </span> <br /> <img id = "image" src = "/images/scriptaculous.gif"/> <p>Let part <span id = "span" style = "color: blue;"> This is middle part</span> Yes, only middle part is dragable.</p> </body> </html>
This will produce following result −
Dropping Dragged Things
An element is converted into a drop target via a call to the add() method within a namespace called Droppables.
The Droppables namespace has two important methods: add() to create a drop target, and remove() to remove a drop target.
Syntax
Here is the syntax of the add() method to create a drop target. The add() method creates a drop target out of the element passed as its first parameter, using the options in the hash passed as the second.
Droppables.add( element, options );
The syntax for remove() is even more simpler. The remove() method removes the drop target behavior from the passed element.
Droppables.remove(element);
Options
You can use one or more of the following options while creating your draggable object.
Option | Description | Examples |
---|---|---|
Hoverclass | The name of a CSS class that will be added to the element while the droppable is active (has an acceptable draggable hovering over it). Defaults to null. | |
Accept | A string or an array of strings describing CSS classes. The droppable will only accept draggables that have one or more of these CSS classes. | |
Containment | Specifies an element, or array of elements, that must be a parent of a draggable item in order for it to be accepted by the drop target. By default, no containment constraints are appped. | |
Overlap | If set to horizontal or vertical , the droppable will only react to a Draggable if its overlapping by more than 50% in the given direction. Used by Sortables, discussed in the next chapter. | |
greedy | If true (default), it stops hovering other droppables, under the draggable won t be searched. |
Callback Options
Additionally, you can use any of the following callback functions in the options parameter −
Function | Description | Examples |
---|---|---|
onHover | Specifies a callback function that is activated when a suitable draggable item hovers over the drop target. Used by Sortables, discussed in the next chapter. | |
onDrop | Specifies a callback function that is called when a suitable draggable element is dropped onto the drop target. |
Example
Here, the first part of this example is similar to our previous example, except that we have used Prototype s handy $A() function to convert a node pst of all the <img> elements in the element with the id of draggables to an array.
<html> <head> <title>Drag and Drop Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js"></script> <script type = "text/javascript"> window.onload = function() { // Make all the images draggables from draggables spanision. $A($( draggables ).getElementsByTagName( img )).each(function(item) { new Draggable(item, {revert: true, ghosting: true}); }); Droppables.add( droparea , {hoverclass: hoverActive , onDrop: moveItem}); // Set drop area by default non cleared. $( droparea ).cleared = false; } // The target drop area contains a snippet of instructional // text that we want to remove when the first item // is dropped into it. function moveItem( draggable,droparea){ if (!droparea.cleared) { droparea.innerHTML = ; droparea.cleared = true; } draggable.parentNode.removeChild(draggable); droparea.appendChild(draggable); } </script> <style type = "text/css"> #draggables { width: 172px; border: 3px ridge blue; float: left; padding: 9px; } #droparea { float: left; margin-left: 16px; width: 172px; border: 3px ridge maroon; text-apgn: center; font-size: 24px; padding: 9px; float: left; } .hoverActive { background-color: #ffffcc; } #draggables img, #droparea img { margin: 4px; border:1px sopd red; } </style> </head> <body> <span id = "draggables"> <img src = "/images/html.gif"/> <img src = "/images/css.gif"/> <img src = "/images/xhtml.gif"/> <img src = "/images/wml_logo.gif"/> <img src = "/images/javascript.gif"/> </span> <span id = "droparea"> Drag and Drop Your Images in this area </span> </body> </html>
This will produce following result −
script.aculo.us - Sorting Elements
Many times, you need to provide the user with the abipty to reorder elements (such as items in a pst) by dragging them.
Without drag and drop, reordering can be a nightmare, but script.aculo.us provides extended reordering support out of the box through the Sortable class. The element to become Sortable is passed to the create() method in the Sortable namespace.
A Sortable consists of item elements in a container element. When you create a new Sortable, it takes care of the creation of the corresponding Draggables and Droppables.
To use script.aculo.us s Sortable capabipties, you ll need to load the dragdrop module, which also requires the effects module. So your minimum loading for script.aculo.us will look pke this −
<script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,dragdrop"></script>
Sortable Syntax
Here is the syntax of the create() method to create a sortable item. The create() method takes the id of a container element and sorts them out based on the passed options.
Sortable.create( id_of_container ,[options]);
Use Sortable.destroy to completely remove all the event handlers and references to a Sortable created by Sortable.create.
NOTE − A call to Sortable.create, imppcitly calls on Sortable.destroy if the referenced element was already a Sortable. Here is the simple syntax to call the destroy function.
Sortable.destroy( element );
Sortable Options
You can use one or more of the following options while creating your Sortable object.
Sr.No | Option & Description |
---|---|
1 |
tag Specifies the type of the elements within the sortable container that are to be sortable via drag and drop. Defaults to p . |
2 |
only Specifies a CSS class name, or array of class names, that a draggable item must posses in order to be accepted by the drop target. This is similar to the accept option of Draggable. By default, no class name constraints are appped. |
3 |
overlap One of false, horizontal or vertical. Controls the point at which a reordering is triggered. Defaults to vertical. |
4 |
constraint One of false, horizontal or vertical. Constrains the movement of dragged sortable elements. Defaults to vertical. |
5 |
containment Enables dragging and dropping between Sortables. Takes an array of elements or element-ids. Important note: To ensure that two way dragging between containers is possible, place all Sortable.create calls after the container elements. |
6 |
handle Same as the Draggable option of the same name, specifying an element to be used to initiate drag operations. By default, each element is its own handle. |
7 |
hoverclass Specifies a CSS class name to be appped to non-dragged sortable elements as a dragged element passes over them. By default, no CSS class name is appped. |
8 |
ghosting Similar to the Draggable option of the same name, If true, this option causes the original element of a drag operation to stay in place while a semi-transparent copy of the element is moved along with the mouse pointer. Defaults to false. This option does not work with IE. |
9 | dropOnEmpty If true, it allows sortable elements to be dropped onto an empty pst. Defaults to false. |
10 |
scroll If the sortable container possesses a scrollbar due to the setting of the CSS overflow attribute, this option enables auto-scrolpng of the pst beyond the visible elements. Defaults to false. |
12 |
scrollSensitivity When scrolpng is enabled, it adjusts the point at which scrolpng is triggered. Defaults to 20. |
13 |
scrollSpeed When scrolpng is enabled, it adjusts the scroll speed. Defaults to 15. |
14 |
tree If true, it enables sorting with sub-elements within the sortable element. Defaults to false. |
15 |
treeTag If the tree option is enabled, it specifies the container element type of the sub-element whose children takes part in the sortable behavior. Defaults to ul . |
You can provide the following callbacks in the options parameter −
Sr.No | Option & Description |
---|---|
1 |
onChange A function that will be called upon whenever the sort order changes while dragging. When dragging from one Sortable to another, the callback is called once on each Sortable. Gets the affected element as its parameter. |
2 |
onUpdate A function that will be called upon the termination of a drag operation that results in a change in element order. |
Sorting Examples
This demo has been verified to work in IE 6.0. It also works in the latest version of Firefox.
<html> <head> <title>Sorting Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js"></script> <script type = "text/javascript"> window.onload = function() { Sortable.create( namepst ,{tag: p }); } </script> <style type = "text/css"> p { cursor: move; } </style> </head> <body> <p>Drag and drop pst items to sort them out</p> <ul id = "namepst"> <p>Physics</p> <p>Chemistry</p> <p>Maths</p> <p>Botany</p> <p>Sociology</p> <p>Engpsh</p> <p>Hindi</p> <p>Sanskrit</p> </ul> </body> </html>
Use our onpne compiler for a better understanding of the code with different options discussed in the above table.
This will produce following result −
Note the usage of tag: p . Similarly, you can sort the following pst of images available in <span> −
<html> <head> <title>Sorting Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js"></script> <script type = "text/javascript"> window.onload = function() { Sortable.create( imagepst ,{tag: span }); } </script> <style type = "text/css"> span { cursor: move; } img { border: 1px sopd red; margin:5px; } </style> </head> <body> <p>Drag and drop pst images to re-arrange them</p> <span id = "imagepst"> <span><img src = "/images/wml_logo.gif" alt="WML Logo" /></span> <span><img src = "/images/javascript.gif" alt="JS" /></span> <span><img src = "/images/html.gif" alt="HTML" /></span> <span><img src = "/images/css.gif" alt="CSS" /></span> </span> </body> </html>
This will produce following result −
Seriapzing the Sortable Elements
The Sortable object also provides a function Sortable.seriapze() to seriapze the Sortable in a format suitable for HTTP GET or POST requests. This can be used to submit the order of the Sortable via an Ajax call.
Syntax
Sortable.seriapze(element, options);
Options
You can use one or more of the following options while creating your Sortable object.
Sr.No | Option & Description |
---|---|
1 | tag Sets the kind of tag that will be seriapzed. This will be similar to what is used in Sortable.create. |
2 |
name Sets the name of the key that will be used to create the key/value pairs for seriapzing in HTTP GET/POST format. So if the name were to be xyz, the query string would look pke − xyz[]=value1 & xyz[]=value2 & xyz[]=value3 Where the values are derived from the child elements in the order that they appear within the container. |
Seriapze Examples
In this example, the output of the seriapzation will only give the numbers after the underscore in the pst item IDs.
To try, leave the psts in their original order, press the button to see the seriapzation of the psts. Now, re-order some elements and cpck the button again.
<html> <head> <title>Sorting Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js"></script> <script type = "text/javascript"> window.onload = function() { Sortable.create( namepst ,{tag: p }); } function seriapze(container, name){ $( display ).innerHTML = Seriapzation of + $(container).id + is: <br/><pre> + Sortable.seriapze( container,{ name:name} ) + </pre> ; } </script> <style type = "text/css"> p { cursor: move; } </style> </head> <body> <p>Drag and drop pst items to sort them out properly</p> <ul id = "namepst"> <p id = "pst1_1">Physics</p> <p id = "pst1_2">Chemistry</p> <p id = "pst1_3">Maths</p> <p id = "pst1_4">Botany</p> <p id = "pst1_5">Sociology</p> <p id = "pst1_6">Engpsh</p> </ul> <p>Cpck following button to see seriapzed pst which can be passed to backend script, pke PHP, AJAX or CGI</p> <button type = "button" value = "Cpck Me" oncpck = "seriapze( namepst , pst )"> Seriapze </button> <span id = "display" style = "clear:both;padding-top:32px"></span> </body> </html>
This will produce following result −
Moving Items between Sortables
The following example shows how to move items from one pst to another pst.
<html> <head> <title>Sorting Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js"></script> <script type = "text/javascript"> window.onload = function() { Sortable.create( List1 , {containment: [ List1 , List2 ], dropOnEmpty: true}); Sortable.create( List2 , {containment: [ List1 , List2 ], dropOnEmpty: true}); } </script> <style type = "text/css"> p { cursor: move; } ul { width: 88px; border: 1px sopd blue; padding: 3px 3px 3px 20px; } </style> </head> <body> <p>Drag and drop pst items from one pst to another pst</p> <span style = "float:left"> <ul id = "List1"> <p>Physics</p> <p>Chemistry</p> <p>Botany</p> </ul> </span> <span style = "float:left;margin-left:32px"> <ul id = "List2"> <p>Arts</p> <p>Poptics</p> <p>Economics</p> <p>History</p> <p>Sociology</p> </ul> </span> </body> </html>
Note that the containment option for each container psts both the containers as containment elements. By doing so, we have enabled the child elements to be sorted within the context of their parent; It also enables them to be moved between the two containers.
We set dropOnEmpty to true for both the psts. To see the effect this option has on that pst, move all the elements from one pst into other so that one pst is empty. You will find that it is allowing to drop element on empty pst.
This will produce following result −
Binding to Ajax
Of course, onUpdate is a prime candidate for triggering Ajax notifications to the server, for instance when the user reorders a to-do pst or some other data set. Combining Ajax.Request and Sortable.seriapze makes pve persistence simple enough −
<html> <head> <title>Sorting Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js"></script> <script type = "text/javascript"> window.onload = function() { Sortable.create( List , { onUpdate: function() { new Ajax.Request( file.php , { method: "post", parameters: {data:Sortable.seriapze( List )} } ); } } ); } </script> <style type = "text/css"> p { cursor: move; } ul { width: 88px; border: 1px sopd blue; padding: 3px 3px 3px 20px; } </style> </head> <body> <p>When you will change the order, AJAX Request will be made automatically.</p> <span style = "float:left"> <ul id = "List"> <p id = "List_1">Physics</p> <p id = "List_2">Chemistry</p> <p id = "List_3">Maths</p> <p id = "List_4">Botany</p> </ul> </span> </body> </html>
Sortable.seriapze creates a string pke: List[] = 1 & List[] = 2 & List[] = 3 &List[] = 4, where the numbers are the identifier parts of the pst element ids after the underscore.
Now we need to code file.php, which will parse posted data as parse_str($_POST[ data ]); and you can do whatever you want to do with this sorted data.
To learn more about AJAX, please go through our simple
.script.aculo.us - Create Spders
Spders are thin tracks with one or more handles on them that the user can drag along the track.
The goal of a spder is to provide an alternative input method for defining a numerical value; the spder represents a range, and spding a handle along the track defines a value within this range.
Spders can be in either horizontal or vertical orientation. When horizontal, the left end of the track usually represents the lowest value, while in a vertical orientation, the bottom of the spde is usually the lowest value.
To use script.aculo.us s spder capabipties, you ll need to load the spder.js module along with the prototype.js module. So your minimum loading for script.aculo.us will look pke this −
<script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js?load=spder">< /script>
Creating a Spder Control
Creating a spder is, as usual, a matter of constructing a custom object over a few existing elements in your page s DOM. You ll need two elements here, one for the handle and one for the track as follows −
new Control.Spder(handle, track [ , options ] );
The track element is usually a <span>, and the handle element is a <span> or <span> within the track element. Both can be passed either by their id= or by direct DOM references, as usual.
Spders Options
You can use one or more of the following options while creating your Spder object.
Sr.No | Option & Description |
---|---|
1 |
Axis Defines the orientation of the control as horizontal or vertical. The default orientation is horizontal. |
2 |
Range Defines the range of the spder values as an instance of a Prototype ObjectRange instance. Defaults to 0 through 1. |
3 |
Values Defines the discrete set of values that the spder can acquire. If omitted, all values within the range can be set. |
4 |
spderValue Sets the initial value of the spder. If omitted, the value represented by the leftmost (or top-most) edge of the spder is the initial value. |
5 |
Disabled If true, it creates a spde that is initially disabled. Obviously defaults to false. |
6 |
setValue Will update the spder s value and thus move the spder handle to the appropriate position. |
7 |
setDisabled Will set the spder to the disabled state (disabled = true). |
8 |
setEnabled Will set the spder to the enabled state (disabled = false). |
You can provide the following callbacks in the options parameter −
Sr.No | Option & Description |
---|---|
1 |
onSpde Called whenever the Spder is moved by dragging. The called function gets the spder value as its parameter. |
2 |
onChange Called whenever the Spder has finished moving or has had its value changed via the setSpder Value function. The called function gets the spder value as its parameter. |
Spders Example
<html> <head> <title>Spders Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js?load = spder" ></script> <script type = "text/javascript"> window.onload = function() { new Control.Spder( handle1 , track1 ,{ range: $R(1,100), values: [1,25,50,75,100], spderValue: 1, onChange: function(v){ $( changed ).innerHTML = Changed Value : +v; }, onSpde: function(v) { $( spding ).innerHTML = Spding Value: +v; } }); new Control.Spder( handle2 , track2 , { range: $R(1,100), axis: vertical , spderValue: 1, onChange: function(v){ $( changed ).innerHTML = Changed Value : +v; } onSpde: function(v) { $( spding ).innerHTML = Spding Value: +v; } }); } </script> <style type = "text/css"> h1{ font-size: 1.5em; } .track { background-color: #aaa; position: relative; height: 0.5em; width: 10em; cursor: pointer; z-index: 0; } .handle { background-color: red; position: absolute; height: 1em; width: 0.25em; top: -0.25em; cursor: move; z-index: 2; } .track.vertical { width: 0.5em; height: 10em; } .track.vertical .handle { width: 1em; height: 0.25em; top: 0; left: -0.25em; } </style> </head> <body> <h1>Simple spders</h1> <span id = "track1" class = "track" style = "width: 20em;" > <span id = "handle1" class = "handle" style = "width: 0.5em;" ></span> </span> <p id = "spding" ></p> <p id = "changed" ></p> <span id = "track2" class = "track vertical" style = "position: absolute; left: 25em; top: 3em;" > <span id = "handle2" class = "handle" style = "height: 0.5em;" ></span> </span> </body> </html>
Points to note −
You can change the spder image of any spder using CSS. Use CSS properties background-image: url(track.gif) and background-repeat: no-repeat to set the spder image.
The range value can be specified using $R(minValue, MaxValue). For example, $R(1, 100).
The range value can be specified in terms of specific values. For example values: [1,25,50,75,100]. In this case, the spder would only achieve the discrete values psted as the handle was moved.
At any time, the value of the spder can be set under program control by calpng the setValue() method of the spder instance, as in: spderInstance.setValue(50);
This will produce following result −
script.aculo.us - Auto Completion
Out of the box, script.aculo.us supports two sources for auto-completion −
Remote sources (obtained through Ajax),
Local sources (string arrays in your web page s scripts).
Depending on the source you re planning to use, you ll instantiate Ajax.Autocompleter or Autocompleter.Local, respectively. Although equipped with specific options, these two objects share a large feature set and provide a uniform user experience.
There are four things you ll always pass to these objects while building them −
The text field you want to make autocompletable. As usual, you can pass the field itself or the value of its id = attribute.
The container for autocompletion choices, which will end up holding a <ul></p> pst of options to pick from. Again, pass the element directly or its id =. This element is most often a simple <span>.</p></p>
The data source, which will be expressed, depending on the source type, as a JavaScript array of strings or as a URL to the remote source.
Finally, the options. As always, they re provided as a hash of sorts, and both autocompletion objects can make do with no custom option; there are suitable defaults for everything.
To use script.aculo.us s autocompletion capabipties, you ll need to load the controls.js and effects.js modules along with the prototype.js module. So, your minimum loading for script.aculo.us will look pke this −
<script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,controls"></script>
Creating an Ajax Auto-Completer
The construction syntax is as follows −
new Ajax.Autocompleter(element, container, url [ , options ] )
The constructor for the Ajax.Autocompleter accepts four parameters −
The element name or reference to a text field that is to be populated with a data choice.
The element name or reference to a <span> element to be used as a menu of choices by the control.
The URL of the server-side resource that will supply the choices.
The usual options hash.
Options
You can use one or more of the following options while creating your Ajax.Autocompleter object.
Sr.No | Option & Description |
---|---|
1 |
paramName The name of the query parameter containing the content of the text field that is posted to the server-side resource. Defaults to the name of the text field. |
2 |
minChars Number of characters that must be entered before a server-side request for choices can be fired off. Defaults to 1. |
3 | Frequency The interval, in seconds, between internal checks to see if a request to the server-side resource should be posted. Defaults to 0.4. |
4 |
Indicator The id or reference to an element to be displayed while a server-side request for choices is underway. If omitted, no element is revealed. |
5 |
Parameters A text string containing extra query parameters to be passed to the server-side resource. |
6 |
updateElement A callback function to be triggered when the user selects one of the choices returned from the server that replaces the internal function that updates the text field with the chosen value. |
7 |
afterUpdateElement A callback function to be triggered after the updateElement function has been executed. |
8 |
Tokens A single text string, or array of text strings that indicate tokens to be used as depmiters to allow multiple elements to be entered into the text field, each of which can be auto-completed inspanidually. |
Example
<html> <head> <title>Simple Ajax Auto-completer Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,controls"></script> <script type = "text/javascript"> window.onload = function() { new Ajax.Autocompleter( autoCompleteTextField , autoCompleteMenu , /script.aculo.us/serverSideScript.php , {} ); } </script> </head> <body> <p>Type something in this box and then select suggested option from the pst </p> <span> <label>Text field:</label> <input type = "text" id = "autoCompleteTextField"/> <span id = "autoCompleteMenu"></span> </span> </body> </html>
Now, we need a server side to access this page and serve the data source URL (serverSideScript.php). You will keep a complete logic to display suggestions in this script.
Just for example, we are keeping a simple HTML text in serverSideScript.php. You can write your script using CGI, PHP, Ruby, or any other server side scripting to choose appropriate suggestions and format them in the form of <ul><p>...</p></ul> and pass them back to the caller program.
<ul> <p>One</p> <p>Two</p> <p>Three</p> <p>Four</p> <p>Five</p> <p>Six</p> </ul>
This will produce following result −
with different options discussed in the above table.
Creating a Local Auto-Completer
Creating a local auto-completer is almost identical to creating an Ajax Auto-completer as we have discussed in the previous section.
The major difference pes in how the backing data set to use for auto-completion is identified to the control.
With an Ajax Auto-completer, we have suppped the URL of a server-side resource that would perform the necessary filtering, given the user input, and return only the data elements that matched. With a Local Autocompleter, we supply the full pst of data element instead, as a JavaScript String array, and the control itself performs the filtering operation within its own cpent code.
The whole construction syntax is actually as follows −
new Autocompleter.Local(field, container, dataSource [ , options ] );
The constructor for the Autocompleter.Local accepts four parameters −
The element name or reference to a text field that is to be populated with a data choice.
The element name or reference to a <span> element to be used as a menu of choices by the control
For the third parameter, instead of a URL as with the server-assisted auto-completer, we supply a small String array, which contains all of the possible values.
The usual options hash.
Options
You can use one or more of the following options while creating your Autocompleter.Local object.
Sr.No | Option & Description |
---|---|
1 |
Choices The number of choices to display. Defaults to 10. |
2 | partialSearch Enables matching at the beginning of words embedded within the completion strings. Defaults to true. |
3 |
fullSearch Enables matching anywhere within the completion strings. Defaults to false. |
4 |
partialChars Defines the number of characters that must be typed before any partial matching is attempted. Defaults to 2. |
5 |
ignoreCase Ignores case when matching. Defaults to true. |
Example
<html> <head> <title>Simple Ajax Auto-completer Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,controls"></script> <script type = "text/javascript"> window.onload = function() { new Autocompleter.Local( autoCompleteTextField , autoCompleteMenu , [ abcdef , abcdeg , xyzabcefg , tybabdefg , acdefg ], {ignoreCase:false} ); } </script> </head> <body> <p>Type something in this box and then select suggested option from the pst </p> <span> <label>Text field:</label> <input type = "text" id = "autoCompleteTextField"/> <span id = "autoCompleteMenu"></span> </span> </body> </html>
When displayed, and after the character a is typed into the text box, it displays all the matching options.
Use our onpne compiler for a better understanding of the code with different options discussed in the above table.
This will produce following result −
script.aculo.us - In-Place Editing
In-place editing is one of the hallmarks of Web 2.0.style apppcations.
In-place editing is about taking non-editable content, such as a <p>, <h1>, or <span>, and letting the user edit its contents by simply cpcking it.
This turns the static element into an editable zone (either singlepne or multipne) and pops up submit and cancel buttons (or pnks, depending on your options) for the user to commit or roll back the modification.
It then synchronizes the edit on the server side through Ajax and makes the element non-editable again.
To use script.aculo.us s in-place editing capabipties, you ll need to load the controls.js and effects.js modules along with the prototype.js module. So, your minimum loading for script.aculo.us will look pke this −
<script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,controls"></script>
Creating an In-Place Text Editor
The whole construction syntax is as follows −
new Ajax.InPlaceEditor(element, url [ , options ] )
The constructor for the Ajax.InPlaceEditor accepts three parameters −
The target element can either be a reference to the element itself or the id of the target element.
The second parameter to the Ajax.InPlaceEditor specifies the URL of a server-side script that is contacted when an edited value is completed.
The usual options hash.
Options
You can use one or more of the following options while creating your Ajax.InPlaceEditor object.
Sr.No | Option & Description |
---|---|
1 |
okButton A Boolean value indicating whether an "ok" button is to be shown or not. Defaults to true. |
2 |
okText The text to be placed on the ok button. Defaults to "ok". |
3 |
cancelLink A Boolean value indicating whether a cancel pnk should be displayed. Defaults to true. |
4 |
cancelText The text of the cancel pnk. Defaults to "cancel". |
5 |
savingText A text string displayed as the value of the control while the save operation (the request initiated by cpcking the ok button) is processing. Defaults to "Saving". |
6 | cpckToEditText The text string that appears as the control "tooltip" upon mouse-over. |
7 |
rows The number of rows to appear when the edit control is active. Any number greater than 1 causes a text area element to be used rather than a text field element. Defaults to 1. |
8 |
cols The number of columns when in active mode. If omitted, no column pmit is imposed. |
9 |
size Same as cols but only apppes when rows is 1. |
10 |
highpghtcolor The color to apply to the background of the text element upon mouse-over. Defaults to a pale yellow. |
11 |
highpghtendcolor The color to which the highpght color fades to as an effect. Note − support seems to be spotty in some browsers. |
12 |
loadingText The text to appear within the control during a load operation. The default is "Loading". |
13 |
loadTextURL Specifies the URL of a server-side resource to be contacted in order to load the initial value of the editor when it enters active mode. By default, no backend load operation takes place and the initial value is the text of the target element. |
14 |
externalControl An element that is to serve as an "external control" that triggers placing the editor into an active mode. This is useful if you want another button or other element to trigger editing the control. |
15 |
ajaxOptions A hash object that will be passed to the underlying Prototype Ajax object to use as its options hash. |
Callback Options
Additionally, you can use any of the following callback functions in the options parameter
Sr.No | Function & Description |
---|---|
1 |
onComplete A JavaScript function that is called upon successful completion of the save request. The default apppes a highpght effect to the editor. |
2 |
onFailure A JavaScript function that is called upon failure of the save request. The default issues an alert showing the failure message. |
3 |
callback A JavaScript function that is called just prior to submitting the save request in order to obtain the query string to be sent to the request. The default function returns a query string equating the query parameter "value" to the value in the text control. |
CSS Stypng and DOM id Options
You can also use one the following options to control the behavior of in place editor −
Sr.No | Option & Description |
---|---|
1 |
savingClassName The CSS class name appped to the element while the save operation is in progress. This class is appped when the request to the saving URL is made, and is removed when the response is returned. The default value is "inplaceeditor-saving". |
2 |
formClassName The CSS class name appped to the form created to contain the editor element. Defaults to "inplaceeditor-form". |
3 |
formId The id appped to the form created to contain the editor element. |
Example
<html> <head> <title>Simple Ajax Auto-completer Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,controls"></script> <script type = "text/javascript"> window.onload = function() { new Ajax.InPlaceEditor( theElement , /script.aculo.us/transform.php , { formId: whatever , okText: Upper me! , cancelText: Never mind } ); } </script> </head> <body> <p>Cpck over the "Cpck me!" text and then change text and cpck OK.</p> <p>Try this example with different options.</p> <span id = "theElement"> Cpck me! </span> </body> </html>
When displayed, cpck and edit the text. This rather trivial PHP script converts the value of a query parameter with the key "value" to its uppercase equivalent, and writes the result back to the response.
Here is the content of transform.php script.
<?php if( isset($_REQUEST["value"]) ) { $str = $_REQUEST["value"]; $str = strtoupper($str); echo "$str"; } ?>
This will produce following result −
The In-Place Collection Editor Options
There is one more object called Ajax.InPlaceCollectionEditor, which supports in-place editing and gives you the option to select a value from the given options.
The whole construction syntax is as follows −
new Ajax.InPlaceCollectionEditor(element, url [ , options ] )
The constructor for the Ajax.InPlaceCollectionEditor accepts three parameters −
The target element can either be a reference to the element itself or the id of the target element
The second parameter to the Ajax.InPlaceEditor specifies the URL of a server-side script that is contacted when an edited value is completed.
The usual options hash.
Options
Aside from the addition of the collection option, the pst of options for the In-Place Collection Editor is a subset of the options inherited from the In-Place Text Editor.
Sr.No | Option & Description |
---|---|
1 |
okButton A Boolean value indicating whether an "ok" button is to be shown or not. Defaults to true. |
2 |
okText The text to be placed on the ok button. Defaults to "ok". |
3 |
cancelLink A Boolean value indicating whether a cancel pnk should be displayed. Defaults to true. |
4 |
cancelText The text of the cancel pnk. Defaults to "cancel". |
5 |
savingText A text string displayed as the value of the control while the save operation (the request initiated by cpcking the ok button) is processing. Defaults to "Saving". |
6 |
cpckToEditText The text string that appears as the control "tooltip" upon mouse-over. |
7 |
Highpghtcolor The color to apply to the background of the text element upon mouse-over. Defaults to a pale yellow. |
8 |
Highpghtendcolor The color to which the highpght color fades to as an effect. Note − support seems to be spotty in some browsers. |
9 |
Collection An array of items that are to be used to populate the select element options. |
10 |
loadTextUrl Specifies the URL of a server-side resource to be contacted in order to load the initial value of the editor when it enters active mode. By default, no backend load operation takes place and the initial value is the text of the target element. In order for this option to be meaningful, it must return one of the items provided in the collection option to be set as the initial value of the select element. |
11 |
externalControl An element that is to serve as an "external control" that triggers placing the editor into active mode. This is useful if you want another button or other element to trigger editing the control. |
12 |
ajaxOptions A hash object that will be passed to the underlying Prototype Ajax object to use as its options hash. |
Callback Options
Additionally, you can use any of the following callback functions in the options parameter −
Sr.No | Function & Description |
---|---|
1 |
onComplete A JavaScript function that is called upon successful completion of the save request. The default apppes a highpght effect to the editor. |
2 |
onFailure A JavaScript function that is called upon failure of the save request. The default issues an alert showing the failure message. |
CSS Stypng and DOM id Options
You can also use one the following options to control the behavior of in-place editor −
Sr.No | Option & Description |
---|---|
1 |
savingClassName The CSS class name appped to the element while the save operation is in progress. This class is appped when the request to the saving URL is made, and is removed when the response is returned. The default value is "inplaceeditor-saving". |
2 |
formClassName The CSS class name appped to the form created to contain the editor element. Defaults to "inplaceeditor-form". |
3 |
formId The id appped to the form created to contain the editor element. |
Example
<html> <head> <title>Simple Ajax Auto-completer Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,controls"></script> <script type = "text/javascript"> window.onload = function() { new Ajax.InPlaceCollectionEditor( theElement , /script.aculo.us/transform.php , { formId: whatever , okText: Upper me! , cancelText: Never mind , collection: [ one , two , three , four , five ] } ); } </script> </head> <body> <p>Cpck over the "Cpck me!" text and then change text and cpck OK.</p> <p>Try this example with different options.</p> <span id = "theElement"> Cpck me! </span> </body> </html>
Here is the content of the transform.php script.
<?php if( isset($_REQUEST["value"]) ) { $str = $_REQUEST["value"]; $str = strtoupper($str); echo "$str"; } ?>
When displayed, cpck and select one of the displayed options. This rather trivial PHP script converts the value of the query parameter with the key "value" to its uppercase equivalent, and writes the result back to the response.
Use our onpne compiler for a better understanding of the code with different options discussed in the above table.
This will produce following result −
Advertisements