jquery tools users guide - common practices for … · jquery is a fast and concise javascript...

24
jQuery Tools Users Guide - Common practices for each of the tools Introduction The Basics Scripting & Events Performance In this document This document describes common practices for each of the tools such as: The role of HTML The role of JavaScript and jQuery The role of CSS Graphic design and Presentation Including the Tools Initializing the Tools Using global configurations Using jQuery Tools plugins and effects The role of HTML jQuery Tools was primarily developed for "normal" HTML developers. You either have an existing website or are starting with a new one and these tools are used to enhance it. The goal here is to use "progressive enhancement" so that browsers that do not support JavaScript at all can still visualize your content. These tools are not bound to any specific HTML structure. For example, tabs can be constructed from ul, ol, dl, div or table elements. The same is true of our other jQuery Tools as well. The most important thing is to understand what you are doing and what HTML element is suitable for which specific situation. All of the tools deal with a root element which is typically a div element, but it does not have to be. For example, a root element for an overlay is the one that contains all overlayed data. In every tool you can have any combination of HTML inside the root element such as images, forms, Flash objects and tables. The role of JavaScript and jQuery jQuery is a fast and concise JavaScript library that simplifies the development of cross-browser applications. All tools except flashembed are dependent on this library. jQuery skills are not required when using these tools. People have been using these tools without any prior

Upload: dinhcong

Post on 10-Sep-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

jQuery Tools Users Guide - Common

practices for each of the tools

Introduction

The Basics

Scripting & Events

Performance

In this document

This document describes common practices for each of the tools such as:

The role of HTML

The role of JavaScript and jQuery

The role of CSS

Graphic design and Presentation

Including the Tools

Initializing the Tools

Using global configurations

Using jQuery Tools plugins and effects

The role of HTML

jQuery Tools was primarily developed for "normal" HTML developers. You either have an

existing website or are starting with a new one and these tools are used to enhance it. The goal

here is to use "progressive enhancement" so that browsers that do not support JavaScript at all

can still visualize your content.

These tools are not bound to any specific HTML structure. For example, tabs can be constructed

from ul, ol, dl, div or table elements. The same is true of our other jQuery Tools as well.

The most important thing is to understand what you are doing and what HTML element is

suitable for which specific situation.

All of the tools deal with a root element which is typically a div element, but it does not have to

be. For example, a root element for an overlay is the one that contains all overlayed data. In

every tool you can have any combination of HTML inside the root element such as images,

forms, Flash objects and tables.

The role of JavaScript and jQuery

jQuery is a fast and concise JavaScript library that simplifies the development of cross-browser

applications. All tools except flashembed are dependent on this library. jQuery skills are not

required when using these tools. People have been using these tools without any prior

knowledge about jQuery and even JavaScript itself. Of course, those skills would be a great help,

but they are not required.

If you want to enhance your jQuery and JavaScript skills, the best things to learn about when

using these tools would definitely be jQuery selectors and object literals. The first skill is used to

select elements from the page to be enhanced with the tools and the latter is used for configuring

the tools. Here is an example that introduces you to both of these skills:

// two jquery selectors and a configuration given as an object literal

$("#content ul.tabs").tabs("div.panes > div", {

// configuration variables

current: 'current',

effect: 'fade'

});

Here we have two jQuery selectors. The first one selects all ul elements whose class name is

tabs which are all contained inside an element whose id is "content". This query is similar to

CSS selectors and if you know CSS, you will feel at home here. The second selector selects all

div elements that are directly nested inside a div whose class name is panes.

Finally, we have a configuration object starting with { and ending with }. It contains a comma-

separated list of name-value pairs. The name is followed by a colon which is followed by a

value. The value can be a number, string, boolean, array, function or another object literal. Care

must be taken to enclose string values in quotes. That is about it. You use this syntax to

configure these tools.

Execute your scripts when the document is ready

It is important that you execute all your scripts only after the document is ready and scriptable.

This can be done by enclosing your JavaScript calls inside a $(document).ready() block

as follows:

$(document).ready(function() {

// put all your JavaScript wizardry here

});

This might be the most important thing in jQuery. Everything inside the block will load as soon

as the document is scriptable but before the whole page contents such as images and Flash are

loaded. Everything that you stick inside the braces is ready to go at the earliest possible moment.

And as opposed to the traditional old-school "onload" attribute in the body tag you can have

multiple $(document).ready() blocks on your page.

You can also use a shorter syntax:

$(function() {

// same thing here.

});

Which does exactly the same thing but is not so intuitive for a newcomer.

The role of CSS

Cascaded Style Sheets (CSS) are the industry standard for styling the presentation and

positioning of your elements. It is a powerful language which can do many things that surprise

even experienced web developers. Learning this skill is definitely encouraged for every web

developer.

These tools are very strict about not mixing any style declarations in the JavaScript code. You

would think that this is an obvious coding principle and should be taken for granted but it isn't.

Taking a quick look at the list of jQuery plugins reveals many tools that mix CSS into their code

and hard code their style. Even if those styling variables are given as configuration variables, be

it borders, images, colors, size or positioning, this leads to poor application design.

A proper tool should only rely on CSS class names - because they offer a much more flexible

styling environment. Let's take the tabs tool as an example. It offers a configuration variable

called current representing a class name that is set to the currently active tab. Lets say you

have set the value "active" as follows:

$("ul.tabs").tabs("div.panes > div", {current: 'active'});

After that you can style the current tab with CSS as follows:

ul.tabs .active {

color: '#fff';

fontWeight: bold;

background-position:0 -40px;

}

This means that you can have a whole CSS arsenal at your disposal while designing what the

currently selected tab should look like. This kind of design principle is used throughout these

tools. There are no hidden surprises in the tools related to styling. The tools are responsible for

setting and removing classes from elements and after that all style is the responsibility of CSS.

You can also customize all class names that these tools use.

Default CSS files

For each tool we offer a default CSS file that you can use as the basis for your design. You can

use the code, images and ideas from there for free. No obligations. They are fully documented

and coded with good CSS practices. For example, you will never see this kind of statement:

/* define colors for body and p elements */

body {

color:#ccc;

}

p {

color:#ccc;

}

Instead it will always be shortened to:

body, p {

color:#ccc;

}

This was just a primitive example of good CSS practice, but it is used extensively in our CSS

files.

Graphic design and presentation

Since you are not tied to any specific HTML/CSS structures, you have lots of freedom in

designing the look and feel of the tools. When designing the presentation of these tools or

basically anything on the web, you have three important but different approaches to choose from.

Now think of designing a rounded box for any content or a tooltip background for example. You

have to choose one design pattern and stick with it. Here are the advantages and disadvantages of

these choices:

1. CSS-based design

This approach depends primarily on CSS for the presentation. You'll use background colors,

border colors and styling, web fonts and have only minimal use of graphics.

limited visual control. There are lots of things you can tweak with CSS, but in the end

they are limited and you simply cannot do everything with them.

scalable size. Your elements can stretch horizontally and vertically without problems.

maintenable. You can easily change the design just by editing a few lines of code.

lightweight. CSS files are text which means that they can be downloaded much faster

than images. CSS files can also be compressed and GZIPped which makes them even

faster.

There are lots of new features in the latest CSS version such as rounded borders, gradient

borders, shadows and opacity, but these are not yet supported by every major browser. Some of

the demos on this site uses these CSS3 features. If you are using Firefox 3.5, Safari 4.0 or other

CSS3 compatible browser please take a look at the scrollable gallery with tooltips demo and

click on the thumbnails. You'll see nice looking drop shadows on the overlay. As you can see

you can create stunning looks by only using CSS and the design will also be well-behaved in

older browsers.

2. Image-based design

In this approach you'll typically use a single background image that is optimized for the purpose.

Best visual control. Your design will look exactly how you want it to look. No

compromises.

Fixed size. Your elements' width and height is fixed. You have to optimize the content to

fit inside elements and for excessive content you must rely on scripting or scrollbars.

Heavy. More kilobytes to download and more requests to the server. Heavy use of

images will slow down your pages.

3. CSS and image-based design

With this approach you'll use a lot of CSS tricks together with multiple background images.

Best of both worlds. Scalable elements that look good.

Lots of work. You must master CSS, and a tight integration with the graphics designer is

needed. This approach requires more planning.

jQuery Tools allows you to use any of above approaches and it does not restrict you to any hard-

coded CSS coding or theming frameworks. Our demo area contains examples of all these

approaches, but we mainly use the second approach. We typically use a single background image

to demonstrate the tool in an appealing manner. We also offer you a lot of different general-use

background images that you can use as the basis for your own design.

PNG-24 format

This website uses a lot of semi-transparent PNG-24 images which are not natively supported by

IE6.

jQuery Tools are proven to work with IE 6.0+ but this website does not optimize the visual

experience for IE6 users.

Because of this and many other huge limitations in IE6 all major players such as YouTube are

dropping the support for IE6. Having said that we can get to the real point.

When saving your web graphics, you should really consider using the PNG-24 file format. It has

support for alpha transparency. This means that you can use any kind of opacity setting on your

image. It's like working with Adobe Photoshop's layers. You can layer multiple PNG images on

top of each other and there is lots of room for experimentation. Below you can see two images.

The gray box is a PNG24 image with alpha transparency.

If you are not using IE6 you can see the eye through the PNG24 image. Many sites don't yet take

full advantage of this wonderful graphics format.

Internet Explorer 6.0

Alpha transparency is not natively supported by Internet Explorer 6.0. It is possible to make

it work in IE6 by using the IE-proprietary AlphaImageLoader filter but, according to recent

studies by Yahoo, this technology should be avoided. The problem with this filter is that it blocks

rendering and freezes the browser while the image is being loaded; it increases memory

consumption and is applied per element, not per image, so the problem is multiplied.

You'll definitely get the most reliable results by using GIF or JPG images in place of PNG

images on IE6. You can override this in your CSS as follows:

#myelement {

background-image: url(corner.png); /* all browsers */

_background-image: url(corner.jpg); /* IE6 only */

}

The initial underscore is a hack that causes the CSS setting to be applied only to versions of IE

older than 7. You may have the patience to do this, but I don't.

PNG24 and opacity in all versions of IE

If you programmatically change the opacity of a PNG image in all versions of Internet Explorer

it will cause ugly black borders around the image as seen in this screenshot:

This bug makes it impossible to make fading animations with PNG images in Internet Explorer.

For this reason the Tooltip "slide" effect uses opacity fading in every browser other than in IE.

This is the default behaviour but you can of course change this if your tooltip is not decorated

with PNG graphics. Take a look at the Tooltip front page and look at the first demo in Firefox

and then in IE. The tooltip fades in/out in Firefox but uses the sliding effect without opacity

changes in IE.

This "black box" bug can also happen in situations where a PNG image is placed on top of a

transparent layer. I noticed this happening in this demo.

Including the Tools

The first thing you must do is include the tools on your pages. You can place the following

statement on your page and you are ready to go:

http://cdn.jquerytools.org/1.2.4/jquery.tools.min.js

This will include the tools on your page with maximum performance. We are offering this high

performance content delivery network (CDN) for free. You can use it in production

environments. Enjoy!

If you are using Firebug or similar JavaScript debugger you can easily test which tools are

included and what are their versions by running the following command from the console:

console.dir($.tools);

You'll see following kind of result

You can see each tool you have included and the version number. If you drill down a little

deeper into these global settings you will see each tool's default configuration values (a good

source of "documentation"!) which are discussed more extensively in the important global

configuration section.

Initializing the Tools

After the needed tools are included on the page, you need to initialize them. All tools follow the

same pattern. Initialization always starts with a jQuery selector followed by the tool initialization

function (constructor) and its configuration object. Here is an example using the scrollable

tool:

// initialize tools.scrollable with configuration variables

$("#wrap").scrollable({

keyboard: false,

circular: true

});

This will make all elements scroll that are contained within an element whose id is "wrap".

Next, comes a tool constructor named scrollable which takes a configuration object as an

argument. This object defines the settings for how we want our elements to be scrolled. This

example above illustrates the general way you will initialize all jQuery Tools.

Return value

The constructor will always return the jQuery object that is a collection of the elements that are

selected by the selector. This is how all proper jQuery plugins are recommended to behave.

Again we use the scrollable tool as our example:

// return elements specified in the selector as a jQuery object

var elements = $("div.scrollable").scrollable();

/*

now you can continue working with the jQuery object. you can,

for example, add new plugins and use built-in jQuery constructs

*/

elements.someOtherPlugin().onClick(function() {

// do something when this element is clicked

});

Using global configurations

Although you can change the default settings of the tools by supplying a configuration in the

initialization phase you may be using the same configuration settings over and over again. In this

case you may want to change the default configuration variables for the tools so that you don't

need to specify the same setting every time. Here is an example of a global configuration setting:

// all overlays use the "apple" effect by default

$.tools.overlay.conf.effect = "apple";

Afterwards you can simply do this:

// "apple" effect is now our default effect

$("a[rel]").overlay();

Of course you can override these default settings just like before:

// override the global configuration setting

$("a[rel]").overlay({effect: 'default'});

Every tool has a global configuration under $.tools.[TOOL_NAME].conf. For example

$.tools.tabs.conf. You can change many global settings simultaneously by using jQuery

built-in $.extend method as follows:

$.extend($.tools.overlay.conf, {

effect: 'apple',

speed: 1000

});

The list of various configuration settings can be found on each individual tool's documentation

page. One important thing about the global configuration is that it provides you a good source of

"documentation". Try typing the following command into your Firebug console:

console.dir($.tools.overlay.conf);

And you should see the following information appear:

Here you can see the available configuration options and their default values. Very useful.

Using jQuery Tools plugins and effects

jQuery Tools is the first framework to take full advantage of jQuery's powerful chaining

technology. Here is an example of a chaining pattern:

// initialize a few scrollables and add more features to them

$(".scroller").scrollable({circular:

true}).navigator("#myNavi").autoscroll({interval: 4000});

You take one or more .scroller elements from a page and make them scrollable. The

scrollable tool has only the absolute necessary features to make things scroll. If you want to have

more features you can use plugins. In this example we used the navigator plugin to setup a

navigator beside the scrollable. The autoscroll plugin makes the items scroll automatically

without any user interaction.

You can have multiple scrollables on the page and they can all be activated with this single line

of code. All plugins may have their own set of configuration variables and they can also be set

from the global configuration.

Almost every tool has a few plugins that can be downloaded from the download page. This kind

of design pattern makes the overall file size dramatically smaller because you can only use the

things you need. It also makes the code more organized and easier to understand. In the

programming world this pattern is called a decorator pattern which is at the heart of jQuery:

"take a bunch of elements from a page and do stuff with them". jQuery Tools takes this seriously

and goes a step further than other libraries.

Every tool has a built-in plugin architecture and you can easily write your own plugins.

Effects

Tabs, tooltip and overlay have a unique "effect framework" which enables you to change the

default behaviour of each tool. Here is an example:

// use the "apple" effect for the overlays

$("a[rel]").overlay({effect: 'apple'});

This configuration makes the overlay use an effect called "apple" which makes the overlay work

as you may have seen on Apple's website. The purpose of the effects is to change the default

behaviour whereas plugins enrich or add new features. In the case of the overlay the actual tool

provides the basic functionality of overlaying such as initialization, keyboard and mouse

interaction and document masking (with the mask tool) while the only job of the effect is to

perform the opening and closing actions of the tool. This makes it fairly easy to implement

different kind of effects. This design pattern makes the code more organized and makes the

overall file size smaller just like the plugins.

Some tools have many built-in effects and some have only one. You can also get more effects

from the download page. You can set the default effect in the global configuration so that you

don't have to explicitly supply it to every initial configuration.

Writing your own effects

Look at each individual tool's documentation for more information:

Writing effects for Tabs

Writing effects for Tooltip

Writing effects for Overlay

Writing effects for Validator

Note: it is possible to define custom configuration variables for your effect by extending the

global configuration. Say you have a custom overlay effect with the configuration property

explosionSpeed; you can give it a default value as follows:

$.tools.overlay.conf.explosionSpeed = 500;

After that the users can either use the default value or override it from the overlay configuration.

jQuery Tools USER'S GUIDE

UI tools

Tabs Slideshow plugin Tooltip Slide effect Dynamic plugin Scrollable Autoscroll plugin

Navigator plugin Overlay Apple effect

Form tools

Dateinput Rangeinput Validator

Toolbox

Flashembed History Expose Mousewheel

report a bug »

Flowplayer

jQuery Tools

Log In

Sign Up

Search

username or e

passw ord

Stay signed in

Login

Forgot your password?

your email

Request password

« Back to login

email

You will recieve your password to this address. Address is not made public.

username

Your preferred username that is used when logging in.

Sign Up

Home Download Demos Documentation Forums

jQuery Tools Users Guide - Common

practices for each of the tools

Introduction

The Basics

Scripting & Events

Performance

In this document

This document describes common practices for each of the tools such as:

API

Events

Writing Plugins

Application Programming Interface (API)

Every tool has a well defined Application Programming Interface (API) that you can work with.

This is one of the greatest strengths of this library. You can call tool methods and access their

properties. The internal state is hidden and private variables are not accessible by the outer world

which is what you would expect from good programming practice. You can get access to the API

by using jQuery's data method. For example

// get access to the API

var api = $("#scroller").data("scrollable");

The argument to the data method is the tool's name. Once you have the API available, you can

start calling its methods. For example:

// we scroll two items forward

api.move(2);

// scroll to the beginning in 2000 milliseconds

api.begin(2000)

// do something upon scroll

api.onSeek(function() {

// inside callbacks the "this" variable is a reference to the API

console.info("current position is: " + this.getIndex())

});

It is natural to have a tool-specific API available when working with a certain widget. There are

no redundant methods and typically you won't need, for example, the DOM manipluation

methods that jQuery offers. You will want to stick with the methods that relate to the task at

hand. There are getters, setters and methods that invoke actions. Invoking methods will always

return the API itself so you can perform method chaining. For example:

// normal API coding that programmers are accustomed to

var index = $("#example").data("tabs").click(1).getIndex();

If your selector returns multiple instances and you want to access a particular API, you can do

following:

// select the correct instance with a jQuery selector

var api = $(".scrollable:eq(2)").data("scrollable");

// or with traversing methods. it is just a matter of taste

api = $(".scrollable").eq(2).data("scrollable");

You can easily see the available API methods a jQuery Tool is using with Firebug. Issue the

console.dir(api); command in Firebug's Console. Here is a screenshot:

This provides you with a good source of "documentation".

jQuery UI unified API

jQuery UI has a so-called "unified API" which uses the following syntax for invoking methods:

// call select method for tabs

$("ul.example").tabs("select", 1);

API methods are called by supplying the method name as a string followed by method

arguments. This kind of syntax is not supported jQuery Tools. To be honest, I think that this kind

API design is fundamentally wrong. It has the following problems:

1. The syntax is unique to jQuery UI and people outside the UI community are not

accustomed to it.

2. The syntax is cubersome. For example, if you want to perform method chaining you have

to write the following: $("ul.example").tabs("select",

1).tabs("disable", 2);

3. The JavaScript engine cannot see typos. writing "selecct" does not produce any errors and

makes it hard to debug.

Deprecated api property

jQuery Tools versions below 1.2 used an "api" configuration property for accessing the api

upon initialization. This property is now deprecated and will be removed in the next version.

Also the ability to access the API by calling the tool constuctor again after the initialization is

deprecated. The data method will only be supported after the next version.

jQuery Tools Events

Every tool is firing events. These are points in time where something critical happens in the tool.

For example, scrollable fires the onSeek event every time scrolling occurs. You can supply

your own event listeners that are called every time an event occurs. These event listeners are

normal JavaScript functions and are the most typical and effective way of extending the

behaviour of jQuery Tools. Event listeners are sometimes called callback functions and both are

valid terms.

Before and after events

These tools provide both the onBefore event which occurs before some action is taken and the

on event that occurs at the time (or after) an action takes place. You can have custom

functionality bound to these events. All tools provide such events and they share a common

naming policy. The onBefore event provides you with the possibility of cancelling the action.

Example

This example demonstrates the onBeforeClick callback function for Tabs:

$("#example").tabs(".panes > div", {

// here is a "normal" configuration variable

current: 'active,

// here is a callback function that is called before the tab is

clicked

onBeforeClick: function(event, tabIndex) {

// the "this" variable is a pointer to the API. You can do a

lot with it.

var tabPanes = this.getPanes();

/*

By returning false here the default behaviour is

cancelled.

This time another tab cannot be clicked when "terms"

are not accepted

*/

return $(":checkbox[name=terms]").is(":checked");

}

});

Supplying Events

There are three different ways of supplying event listeners:

1. In the configuration

You can supply your event listeners directly in the configuration when the tool is initialized. For

example:

$(".tabs").tabs({

// do your own stuff here

onClick: function() {

// "this" is a reference to the Tabs API

var tabPanes = this.getPanes();

}

});

This is the most common way to supply callbacks and is suitable for most of the situations. The

biggest drawback to this method is that you can supply only one callback for each event. For

example, you cannot define two different onClick event listeners in the same configuration.

Note: in the above example the this variable is a reference to the Tabs API.

2. Using jQuery's bind method

This is a standard way of assigning callback methods in jQuery land. Here is an example:

// first callback

$(".tabs").bind("onClick", function() {

// "this" is a reference to the DOM element

var ulElement = this;

// another one

}).bind("onClick", function() {

});

The bind method can be called multiple times so you can assign multiple onClick listeners

(also known as "chaining"). This is crucial when developing jQuery Tools plugins.

By using the bind method you can use the whole event binding arsenal that jQuery provides

such as unbind for removing event listeners and one for calling your listener only once. The

jQuery documentation for the bind method is good reading and describes you the basics of event

binding. It also talks about advanced topics such as namespacing which are also valid in jQuery

Tools.

Inside your event listener the this variable is a reference to the DOM element returned by the

jQuery selector just like jQuery programmers are accustomed to.

By far the best thing about the bind method is that you can bind the same event listener to

multiple instances with the same call. If for example the selector .tabs in our above example

returns multiple instances, the bind method will assign the listener to all instances

simultaneously. Also note that bind allows you to supply multiple events types with the same

call. For example:

// the same event listener is called before *and* after a tab is clicked

$(".tabs").bind("onBeforeClick onClick", function() {

});

3. Supplying listeners from the API

Each jQuery Tool allows you to supply the event listeners from the API. For example:

// grab the API with jQuery's data method

var api = $(".tabs").data("tabs");

// supply an event listener

api.onBeforeClick(function() {

// supply another

}).onClick(function() {

});

Inside the event listener the this variable is a reference to the Tools API and you can chain the

methods "normally". This syntax follows a more traditional programming style that is more

fluent and understandable for people outside the jQuery community.

// loop through each instances

$(".tabs").each(function() {

// assign the onClick listener to a single instance

$(this).data("tabs").onClick(function() {

});

});

The Event object

Every callback function receives the jQuery.Event object as the first argument for the callback

function. This event object standardizes the event processing according to the W3C standards.

Here are some things you can do with this object:

// the event object is the first argument for *all* callbacks in jQuery Tools

api.onClick(function(event) {

// cancel the default action.

// same as using "return false;" as the last line of this code block.

event.preventDefault();

/* If you have multiple callbacks of the same type this prevents

the rest of the callbacks from being executed. */

event.stopImmediatePropagation();

// retrieve the value returned by the previous callback function

event.result;

// The timestamp (in milliseconds) of when the event was created.

event.timeStamp;

// mouse position when event was fired

var x = event.pageX;

var y = event.pageY;

// whether CTRL, ALT, SHIFT or ESC was being pressed

var alt = event.altKey,

ctrl = event.ctrlKey,

shift = event.shiftMey,

esc = event.metaKey;

// the original triggering element

var element = e.originalTarget || e.srcElement;

});

Within the scope of jQuery Tools, the preventDefault() is identical to returning false

from the callback. This is just a matter of style where the preventDefault() is the modern

manner of cancelling.

You can get the handle to the actual element that fired the event with var element =

e.originalTarget || e.srcElement;. For example, you can get a handle to the

scrollable navigator item that was clicked inside the onSeek event.

A quick comparison with class-based inheritance

Some programmers may argue that a better solution would have been to implement "classes" that

users can "extend". Trust me, it's not. JavaScript is an inherently functional language, not an

object-oriented one. Trying to mimic classical inherintance leads to poor design and makes

programs longer and harder to understand. This is especially important in jQuery development

because this library itself is highly dependent on callbacks and does not support any kind of

inheritance. Functions are an easy, light-weight and effective way of extending behavior. Even

newcomers can use them without understanding the anatomy of the JavaScript language.

Creating jQuery Tools Plugins

It is possible to implement jQuery plugins that are tightly integrated with jQuery Tools. These

plugins would typically alter the default behaviour of a tool or they can add new functionality.

jQuery Tools plugins are authored just like normal jQuery plugins with the exception that inside

your plugin you'll get a handle to the Tools programming API and possibly supply callback

functions. The fact that the tools can have an unlimited number of callback functions registered

is the backbone of plugin development. Here is a simple skeleton for a plugin that will track

Google Analytics each time a tab is clicked:

// create jQuery plugin called "analytics"

$.fn.analytics = function(tracker) {

// loop through each tab and enable analytics

return this.each(function() {

// get handle to tabs API.

var api = $(this).data("tabs");

// setup onClick listener for tabs

api.onClick(function(event, index) {

tracker.trackEvent("tabs", "foo", index);

});

});

};

After you have this plugin included on your page, you can use the plugin in the following

manner:

// initialize tabs and the analytics plugin. the Analytics tracker argument

is defined elsewhere

$("ul.tabs").tabs("div.panes > div").analytics(tracker);

If you are a jQuery plugin developer, you can see that this follows the "standard" way of

developing plugins. Our setup requires that the tabs are initialized before the analytics plugin, so

you cannot write:

// this is wrong. the analytics plugin does not get access to the tabs API

$("ul.tabs").analytics(tracker).tabs("div.panes > div");

Here is a relatively sane writing about developing jQuery plugins. There are many plugins

available on the download page. You can take a look at their commented source code to get a

better understanding of plugin development.

Flowplayer

jQuery Tools

Log In

Sign Up

Search

username o

password

Stay signed in

Login

Forgot your password?

your email

Request password

« Back to login

email

You will recieve your password to this address. Address is not made public.

username

Your preferred username that is used when logging in.

Sign Up

Home Download Demos Documentation Forums

jQuery Tools Users Guide - Common

practices for each of the tools

Introduction

The Basics

Scripting & Events

Performance

80-90% of the end-user response time is spent on the front-

end.

Start there.

This result has been identified by Yahoo engineers in their famous article Best Practices for

Speeding Up Your Web Site. Most front-end time is tied up in downloading all the components

on the page: images, stylesheets, scripts, Flash, etc. As a website developer, you should focus on

this fact first rather than focusing on other areas such as backend optimization. Here are the

primary rules that make your site work faster:

1. Make fewer HTTP requests

2. Use a Content Delivery Network (CDN)

3. Add an Expires header

4. GZIP components

8. Minimize the JavaScript

By focusing on these areas, you can improve your website performance by roughly 70-80%. If

this is hard to believe, I suggest you read the Yahoo white-paper.

jQuery Tools respects all 5 rules

By including jQuery Tools on your pages with following statement:

<script src="http://cdn.jquerytools.org/1.2.4/jquery.tools.min.js"></script>

You should respect all five of the Yahoo performance rules mentioned above. We are offering

this high performance content delivery network (CDN) for free. You can use it in all

environments including production environments. Enjoy! If you are concerned about the file size

you should download a combined script that contains only those tools that you really need and

follow the principles that are mentioned in this document.

1. Make fewer HTTP requests

You might be familiar with following setup at the beginning of your page:

<script src="js/jquery.js"></script>

<script src="js/tabs.js"></script>

<script src="js/lightbox.js"></script>

<script src="js/another-plugin.js"></script>

...

And immediately after that setup you have noticed that your pages are much slower and you still

have more plugins to be included. What an unbearable situation. This is the biggest reason for

slow pages - lots of included scripts, CSS files and images. With jquery.tools you'll end up

having the following setup:

<script src="http://cdn.jquerytools.org/1.2.4/jquery.tools.min.js"></script>

This will include both the latest jQuery library and all the tools in a single file. Due to the fact

that these tools are very generic in nature you may find yourself in a situation that you don't need

a lot of other libraries on your pages. Many times you have your own site-wide JavaScript library

that does all the custom stuff you need. If you are still in doubt that this is important, you should

take a look at following online tests by Steve Souders:

Separate script files

Combined script file

The first example has five included scripts and it takes roughly 3 seconds to load and the second

one has the same scripts in one combined file and it takes roughly 1 second to load - that is a

noticeable improvement.

2. Use a CDN

CDN stands for Content Delivery Network and is a collection of web servers distributed across

the globe to deliver content to users more efficiently. When a user accesses a file from Europe,

then it is served from a server that is located in Europe. The same with with users in the United

States and Asia.

Our CDN service is kindly provided by Max CDN and you can use it freely in any situation.

Enjoy! Here is their global server distribution at the moment - they are all serving these tools

quickly:

location servers

North Chicago, Miami, Dallas, New York, Los Angeles, Atlanta, Seattle,

location servers

America Washington, DC/Ashburn, San Jose

Europe Amsterdam, Frankfurt and London in the UK

Asia Spring 2010

Generally, the files fetched from a CDN load 15-20% faster than without a CDN. You can prove

this to yourself with this live example. If your website is viewed globally, we strongly

recommend that you make a deal with a CDN provider. It is not a very complex procedure.

3. Add an Expires header

Adding an Expires header to your components with a date in the future makes them cacheable,

reducing the load time of your pages. This won't affect performance the first time users hit your

page, but on subsequent page views it could reduce response times by 50% or more. So we are

talking about serious improvements here. For example, in Java Servlets you'll do this with the

following call:

response.setHeader("Cache-Control", "max-age=315360000");

This will set the Expires header 10 years ahead which will do the job. The Tools under

http://cdn.jquerytools.org have their Expires headers set correctly.

4. GZIP components

This is another huge performance saver and cuts down the file size roughly 65%. All modern

browsers support gzipped files and are able to extract them before usage. There is absolutely no

reason why you shouldn't compress them.

Approximately 90% of today's Internet traffic travels through browsers that claim to support

gzip. You can test the response time improvement of gzipped components from this live

example. The Tools under http://cdn.jquerytools.org are gzipped. Look at your web

server documentation on how to enable gzipping. This is possible in every major server such as

Apache, Tomcat or lighttpd.

8. Minify JavaScript

Minification is the practice of removing unnecessary characters from code to reduce its size

thereby improving load times. When code is minified all comments are removed, as well as

unneeded white space characters (space, newline, and tab). In a survey of ten top U.S. web sites,

minification achieved a 21% size reduction.

jQuery Tools are minified with the Google Closure Compiler.

The Closure Compiler is a JavaScript minifier designed to be 100% safe and yield a higher

compression-ratio than most other tools.

Note: Although packed scripts usually have smaller file sizes, they offer less performance than

minified scripts. See the details of various compression schemes in this JavaScript Library

Loading Speed article. For this reason, jQuery Tools are minified and not packed.