• USA : +1 973 910 5725
  • INDIA: +91 905 291 3388
  • info@tekslate.com
  • Login

jQuery Tutorials

jQuery Tutorials Overview

Welcome to jQuery Tutorials. The intent of the tutorials is to provide in depth understanding of jQuery. Apart from the tutorials, we will also cover jQuery Interview Questions.

Introduction to jQuery

jQuery is a fast and concise JavaScript library created by John Resig in 2006 with a nice motto: Write less, do more

jQuery simplifies HTML document traversing, event handling , animating, and ajax interactions for Rapid Web Development.

What you should already know

Before you start studying jQuery, you should have a basic knowledge of :

HTML

CSS

JavaScript

What is jQuery?

jQuery is a JavaScript toolkit designed to-simplify various tasks by writing less code. Here is the list of important core features supported by jQuery

DOM manipulation 

The jQuery made it easy to select DOM elements, traverse them and modifying their content by using cross-browser selector engine called sizzle.

Event handling 

The jQuery offers an elegant way to capture a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers.

Ajax support 

The jQuery helps you a lot to develop a responsive and feature-rich site using AJAX technology.

Animations

The jQuery with plenty of built-in animation effects which you can use in your websites.

Lightweight 

The jQuery is very light weight library- about 19KB in size(Minified and gzipped)

Cross Browser Support

The jQuery has cross-browser support, and works well in IE 6.0+, FF 2.0 + , Safari 3.0 +, Chrome and Opera 9.0 +

Latest Technology 

The jQuery supports CSS3 selectors and basic Xpath syntax

jQuery Cheat Sheet

Here is a quick jquery Cheat Sheet for you to download.

Adding the jQuery Library to your pages

The jQuery library is stored as a single JavaScript file, containing all the jQuery methods. It can be added to a web page with the following mark-up:

<head>
<script type=”text/javascript”src=”jQuery.js”></script>
</head>

Please note that the <script> tag should be inside the page’s <head> section.

Basic jQuery Example

The following example demonstrates the jQuery hide() method, hiding all <p> elements in an HTML document

Example

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>
<script type=”text/javascript”>

$(document).ready(function()) {

$(“button”).click(function()) {

$(“p”).hide();

}};

</script>

</head>

<body>

<h2>This is heading </h2>

<p>This is a paragraph</p>

<p> This is another paragraph.</p>

<button> click me</button>

</body>

</html>

Downloading jQuery

Two versions of jQuery are available for downloading : one minified and one uncompressed (for debugging or reading)

Both versions can be downloaded from jQuery.com

Alternatives to Downloading

If you don’t want to store the jQuery library on your own computer, you can use the hosted jQuery library from Google or Microsoft.

Google

<head>

<script name=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jQuery/1.4.2/jQuery.min.js”></script>

</head>

Microsoft

<head>

<script type=”text/JavaScript” src=”http://ajax.microsoft.com/ajax/jQuery/jQuery1.4.2.min.js”></script>

</head>

jQuery Syntax

with jQuery you select(query) HTML elements and perform “actions” on them

The jQuery syntax is tailor made for selecting HTML elements and perform some action on the element(s)

Basic syntax is : $(selector).action()

A dollar sign to define jQuery

A(selector) to “query(or find)” HTML elements

A jQuery action() to the performed on the elements

Examples 

$(this).hide() – hides current element

$(“p”).hide() – hides all paragraphs.

$(“p.test”).hide() – hides all paragraphs with class = “test”

$(“#test”).hide() – hides the element with id =”test”

<html>

<head>

<script type=”text/JavaScript” src=”jQuery.js”></script>

<script type=”text/JavaScript”>

$(document).ready(function()) {

$(document).click(function()) {

$(this).hide();

})

</script>

</head>

<body>

<button>click me</button>

</body>

</html>

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function()) {

$(document).click(function()) {

$(“#this”).hide();

});

});

</script>

</head>

<body>

<h2>This is a heading</h2>

<p> This is a paragraph.</p>

<p id=”test”> This is another paragraph.</p>

<button>click me</button>

</body>

</html>

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function()) {

$(“button”).click(function()) {

$(“p”).hide();

});

});

</script>

</head>

<body>

<h2>This is a heading</h2>

<p> This is a paragraph.</p>

<p>This is another paragraph</p>
<button>click me</button>

</body>

</html>

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function()) {

$(“button”).click(function()) {

$(“.test”).hide();

});

});

</script>

</head>

<body>

<h2 class=”test”> This is  a heading</h2>

<p class=”test”>This is a paragraph</p>

<button>click me</button>

</body>

</html>

Note

jQuery uses a combination of Xpath and CSS slector syntax

jQuery Basics

jQuery is a framework built using JavaScript capabilities. So you can use all the functions and other capabilities available in JavaScript.

String

A string in JavaScript is an immutable object that contains, none, one or many characters.

Following are the valid examples of a JavaScript string :

“This is JavaScript string”

‘This is JavaScript string’

‘ This is “really” a JavaScript string ‘

“This is ‘really’ a JavaScript string”

Numbers

Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are immutable , just as strings.

Following are the valid examples of a JavaScript Numbers:

5350

120.27

0.26

Boolean 

A boolean in JavaScript can be either or false. If a number is zero, it defaults to false, if an empty string defaults to false.

Following are the valid examples of a JavaScript Boolean :

true            //      true

false           //      false

0                 //      false

}                  //      true

“”                //      false

“hello”       //      true

Objects

JavaScript supports object concept very well. You can create an object using the object literal as follows:

varemp= {

name: “zara”,

age: 10

}’

You can write and read properties of an object using the dot notation as follows :

// getting object properties

emp.name           //      == > Zara

emp.age              //      == > 10

// setting object properties

emp.name=”Daisy” //           <== Daisy

emp.age=20                 //      <== 20

Arrays

You can define arrays using the array literal as follows :

var x=[];

var y=[1,2,3,4,5];

An array has a length property that is useful for iteration:

var x=[1,2,3,4,5];

for(vari=0;i<x.length;i++)

{

// Do something with x[i]

}

Functions

A function in JavaScript can be either named or anonymous. A named function can be defined using function keyword as follows :

function named()

{

// do some stuff here

}

An anonymous function can be defined in similar way as a normal function but it would not have any name. A anonymous function can be assigned to a variable or passed to a method as shown below.

var handler = function()

{

// do some stuff here

}

Jquery makes a use of anonymous funcitons very frequently as follows :

$(document).ready(function()) {

// do some stuff here

}};

Arguments 

JavaScript variable arguments is a kind of array which has length property. Following example explains it very well :

functionfunc(x)

{

console.log(typeofx,arguments.length);

}

func();        // == > “undefined”,0

func(1);      // == > “number”,1

func(“1”,”2”,”3”);        // == >”string”,3

The arguments object also has a callee property. which refers to the function you ‘re inside of. For example:

functionfunc()

{

return.arguments.callee;

}

func();        //  == >func

Scope

The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.

Global Variable 

A global variable has global scope which means it is defined everywhere in your JavaScript code.

Local Variable 

A Local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

Within body of a function, a local variable takes precedence over a global variable with the same name :

varmyvar=”global”                //== > Declare a global variable

function()

{

varmyvar=”local”;       // == > Declare a local variable

document.write(myvar);      //== > local

Built – in Functions

JavaScript comes along with useful set-of built- functions. These methods can be used to manipulate string Numbers and Dates

Following are important JavaScript functions

Method Description
charAt() Returns the character at the specified index
contact() Combines the text of two strings and returns a new string.
forEach() Calls a function for each element in the array
indexof() Returns the index within the calling string object of the first occurrence of the specified value or -1 if not found.
length() Returns the length of the string
pop() Removes the last element form an array and returns the new length of the array.
push() Adds one or more elements to the end of an array and returns the new length of the array
reverse() Reverses the order of the elements of an array – the first becomes the last, and the last becomes the first
sort() Sorts the elements of an array
substr() Returns the characters in a string beginning at the specified location through the specified number of characters
toLowerCase() Returns the calling string value converted to lower case.
toString() Returns the string representation of the number’s value
toUppercase() Returns the calling string value converted to uppercase.

jQuery  Selectors

A jQuery selector is a function which makes use of expressions to find out matching elements form a DOM based on the given criteria.

How to use Selectors ?

The selectors are very useful and would be required at every step while using jQuery. They get the exact element that you want from your HTML document.

Following table lists down few basic selectors and explains them with examples.

Selector Description
#ID Selects all elements which match with the given element Name.
class Selects a single element which matches with the given ID
Universal(*) Selects all elements available in a DOM
Multiple Elements E,F,G Selects the combined results of all the specified selectors E,F or G

JQuery CSS Element Selector

Description

The element selector selects all the elements that have a tag name of T.

Syntax:

Here is the simple syntax to use this selector :

$(‘tagname’) 

 

Parameters

Here is the description of all parameters used by this selector:

tagname : Any standard HTML tag name like div,p,em,img,lietc

Returns

Like any other JQuery selector, this selector also returns an array filled with the found elements.

Example

$(‘p’) selects all elements with a tag name of p in the document

$(‘div’) selects all elements with a tag name of div in the document.

Following example would select all the divisions and display them one :
<html>

<head>

<title>The Selector Example</title>

<script type=”text/javascript” src=”/jquery/jquery-1.3.2.min.js”>

</script>

<script type=”text/javascript” language=”javascript”>

$(document).ready(function()) {

/* This would select all the divisions */

vardivs = $(“div”);

for(i=0;i<divs.length;i++)

{

alert(“Found Division:” + divs[i].innerHTML);

}

}};

</script>

</head>

<body>
<div class=”div1” id=”divid1”>

<p class = “para1” id=”pid1”>This is first paragraph. </p>

<p class=”para2” id=”pid2”> This is second paragraph.</p>

<p class=”para3” id=”pid3”>This is third paragraph. </p>

</div>

<br/>

<div class=”div2” id = “divid2”>

<p>This is second division of the DOM. </p>

</div>

<br/>

<div class=”div3” id=”divid3”>

<p>This is a para inside third division</p>

</div>

</body>

</html> 

 

JQuery CSS Element ID Selector

Description

The element ID selector selects a single element with the given id attribute.

Syntax 

Here is the simple syntax to use this selector

$(‘#elementid’)

Parameters

Here is the description of all the parameters used by this selector :

elementid

This would be an element ID. If the id contains any special characters like periods or colons you have to escape those characters with backslashes

Returns

Like any other JQuery selector, this selector also returns an array field with the found element.

Example

$(#myid) selects element with the given id myid.

$(‘div#yourid’) selects a single division with the given id yourid.

Following example would select second division and display its cotent:

<html>

<head>

<title> The selecter Example</title>

<scrit type=”text/javascriptsrc=”/jquery/jquery-1.3.2.min.js”>

</script>

<script type=”text/javascript” language=”javascript”>

$(document).ready(function()) {

vardivs=$(“#divid2”);

alert(“Found Division:.” + divs[0].innerHTML)

}};

</script>

</head>

<body>

<div class= “div1” id=”divid1”>

<p class=”para1” id=”pid1”>This is first paragraph </p>

<p class=”para2” id =”pid2”>This is second paragraph</p>

<p class=”para3” id=”pid3”>This is third paragraph</p>

</div>

<br/>

<div class=”div2” id=”divid2”>

<p>This is second division of the DOM.</p>

</div>

<br/>

<div class =”div3” id =”divid3”>

<p>This is a para inside third division</p>

</div>

</body>

</html>

jQuery CSS Element Class Selector

Description

The element class selector all the elements which match with the given class of the elements.

Syntax

Here is the simple syntax use this selector:

$(‘.classid’)

Parameters

Here is the description of all parameters used by this selector.

classid: This is class ID available in the document.

Returns

Like any other jQuery selector, this selector also returns an array filled with the found elements.

Example

$(‘.big’) selects all the elements with the given class ID big.

$(‘p.small’) selects all the paragraphs with the given class ID small.

$(‘big.small’) selects all the elements with a class of big and small.

Following example would select all divisions with class.big and display its content:

<html>

<head>

<title> the selector Example</title>

<script type=”text/javascrpit” language =”javascrpit”>

$(document ).ready (function(){

vardivs=$(“div”);

for(i=0;i<divs.length;i++){

alert(“Found Division :”+divs[i].innerHTML);

}

});

</script>

</head>

<body>

<div class=”big” id=”divid1”>

<p class=”para1” id=”pid1”>This is first paragraph. </p>

<p class=”para2” id=”pid2”>This is second paragraph. </p>

<p class=”para3” id=”pid3”>This is third paragraph. </p>

</div>

<br/>

<div class =”big” id =”divid2”>

<p> This is second division of the DOQ.</p>

<p> This is Second para inside second division.</p>

</div>

<br/>

<div class=”medium” id =”divid3”>

<p> This is a para inside third division.</p>

</div>

</body>

</html>

jQuery CSS Universal Selector

Description

The universal selector selects all the elements available in the document.

Syntax

Here is the simple syntax to use this selector:

$(‘*’)

Parameters

Here ia the description of all the parameters used by this selector.

*:A symbolic star.

Returns

Like any other jQuery selector, this selector also returns an array filled with the found elements.

Example

$(‘*’) selects all the elements available in the document

Following example would select all the elements available and would display them one by one:

<html>

<head>

<title> The selector Example</tittle>

<script type=”text/JavaScript” language=”javascript”>
$(document).ready(function(){

var elements=$(“*”);

for(i=0; i<elements.length; i++){

alert(“Found element:”+elements[i].innerHTML);

}

});

</script>

</head>

<body>

<div class=”big” id =”divid2”>

<p>This is second division of the DOM</p>

<p>This is second para inside second division </p>

</div>

<br/>

<div class=”medium” id =”divid3”>

<p>This is a para inside third division</p>

</div>

</body>

</html>

jQuery-CSS Multiple Elements E,F,G Selector

Description

This Multiple Elements selects the combined results of all the specified selectors E,F or G.

You can specify any number of selectors to combine into a single result. Here order of the DOM elements in the jQuery object aren’t necessarily identical. 

 

Syntax

Here is the simple syntax to use this selector:

$(‘E, F, G,…..’)

Parameters

Here in the description of all parameters used by this selector:

E:Any valid selector

F:Any valid selector

G: Any valid selector

Returns

Like any other JQuery selector, this selector also returns an array filled with the found elements.

Example

$(‘div,p’) : selects all the elements matched by div or p.

$(‘p strong ,.myclass’) : selects all the elements matched by strong that are descendants of an element matched by p as well as all elements that have a class of myclass.

$(‘p strong ,#myid’) :selects asingle elements matched by strong that is descendant of an element matched by p as well as elemera whose id is myid.

Following example  would select elements with class ID big and element with ID divid3:

<html>

<head>

<title> The selector Example </title>

<script type=”text/javascrpit” src=”/jquery/jquery-1.3.2.min.js>

</script>

<script type=”text/javascrpit” language=”javascript”>

$(document).ready (function() {

var elements =$(“.big, #divid3”);

for(i=0;i<elements.length; i++){

alert(“Found element:”+elements[i].innerHTML);

}

});

</script>

</head>

<body>

<div class =”big” id=”divid1”>

<p class=”para1” id =”pid1”>This is first paragraph</p>

<p class=”para2” id =”pid2”>This is second paragraph</p>

<p class=”para3” id =”pid3”>This is third paragraph</p>

</div>

<br/>

<div class =”big” id =”divid2”>

<p>This is second division of the DOM</p>

<p>This is second para inside second division </p>

</div>

<br/>

<div class =”medium” id =”divid3”>

<p>This is a para inside third division </p>

</div>

</body>

</html>

Selector Example Selects
* $(“*”) All elements
#id $(“#lastname”) The elements with id=lastname
.class $(“.intro”) All the elements with id=lastname
element $(“p”) All p elements
.class.class $(.intro.demo) All elements with the classes “intro” and “demo”
:first $(“p:first”) The first p element
:last $(“p:last”) The last p element
:even $(“tr.even”) All even tr elements
:odd $(“tr.odd”) Alll odd tr elements
:eq(index) $(“ulli:eq(3)”) The fourth element in list (index starts at 0)
:gt(no) $(“ulli:gt(3)”) list elements with an index greater than 3
:lt(no) $(“ulli:lt(3)”) list elements with an index less than 3
:not(selector) $(“input:not(:empty)”) All the inputs elements that are not empty.
:header $(“:header”) All header elements h1, h2….
:animated $(“:animated”) All animated elements
:contains(text) $(“:contains(‘W3Schools’)”) All elements which contains the text.
:empty $(“:empty”) All elements with no child (elements) nodes
:hidden $(“p:hidden”) All hidden p elements
:visible $(“table:visible”) All visible tables
s1,s2,s3 $(“th,td,.intro”) All elements with matching selectors
[attribute] $(“[href]”) All element with a href attribute.
[attribute=valve] $(“[href=’default.htm’]”) All elements with a href attribute value equal to “default.htm”
[attribute!=value] $(“[href1=’default.htm’]”) All elements with a href attribute value not equal to “default.htm”
[attribute$=valve] $(“[href$=’.jpg’]”) All elements with a  href attribute value ending with “.jpg”
:input $(“.input”) All input elements
:text $(“.text”) All input elements with type=”text”
:password $(“:password”) All input elements with type=”password”
:radio $(“:radio”) All input elements with type =”radio”
:checkbox $(“:checkbox”) All input elements with type =”checkbox”
:submit $(“:submit”) All input elements with type=”submit”
:reset $(“:reset”) All input elements with type=”reset”
:button $(“:button”) All input elements with type=”button”
:image $(“:image”) All input elements with type=”image”
:file $(“:file”) All input elements with type=”file”
:enabled $(“:enabled”) All  enabled input elements
:disabled $(“:disabled”) All disabled input elements
:selected $(“:selected”) All selected input elements
:checked $(“:checked”) All selected input elements

Similar to above syntax and examples, following example would give you understanding on using different type of other useful selectors

$(‘*’)    2 This selector selects all elements in the document.

$(“p>*”)2 This selector selects all elements that are children of a paragraph element.

$(“#specialID”)2:This selector function gets the element with id=”specialID”.

$(“.specialClass”)2 This selector gets all the elements that have the class of specialClass.

$(“li:not(.myclass)”)2Selects all elements matchbody <li> that do not have class=”my class”.

$(“a#specialID.specialClass”)2This selector matches links with an id of specialID and a class of specialClass.

$(“p a.specialClass”)2 This selector matches links with a class of specialclass declared with in <p> elements.

$(“ulli:first”)2 This selector gets only the first <li> elementof the <ul>.

$(“container p”)2 Selects all elements matched by <p> that are descendants of an element that has an id of container.

$(“li>ul”)2Select all elements matched by <ul> that are children of an element matched by <li>

$(“strong+em”)2Selects all elements matched by <em> that immediately follow a sibling element matched by <strong>

$(“p~ul”) 2Selects all elements matched by <ul> that follow a sibling element matched by <p>.

$(“code, em, strong)2Selects all elements matched by <code> or <em>or <strong>.

$(“p strong ,.myclass”)2 Selects all elements matched by <strong> that are descendants of an element matched by <p> as well as all elements that have a class of myclass.

$(“.empty”)2 Selects all elements that have no children.

$(“p:empty”)2Selects all elements matched by <p> that have no children.

$(“div[p]”)2Selects all elements matched by <div> that contain an element matched by <p>

$(“p[.my class]”)2Selects all elements matched by <p> that contain an element with aclass of myclass.

$(“a[@rell]”)2Selects all elements matched by<a> that have a rel attribute.

$(“input[@name=myname]”)2Selects all elements matched by <input> that have a name value exactly equal to myname.

$(“input[@name^=myname]”)2Selects all elements matched by <input> that have a name value beginning with myname.

$(“a[@rel$=self]”)2Selects all elements matched by <p> that have a class value ending with bar.

$(“a[@href*=domain.com]”)2 Selects all elements matched by <a> that have an href value containing domain.com.

$(“li:even”)2Selects all elements matched by <li>that have an even index value.

$(“tr:odd”)2Selects all elements matched by <tr> that have an odd index value.

$(“li:first”)2Selects all the first<li> element.

$(“li:last”)2Selects all the last <li> element.

$(“li:visible”)2Selects all the element matched by<li> that are visible.

$(“li:hidden”)2Selects all elements matched by <li> that re hidden.

$(“:radio”)2Selects all radio buttons in the form.

$(“:checked”)2Selects all checked boxex in the form.

$(“:input”)2Selects only form elements (input, select, textarea, button).

$(“:text”)2 Selects only text elements(input[type=text]).

$(“li:eq(2)”)2 Selects the third <li> element.

$(“li:eq(4)”)2 Selects the fifth <li> element

$(“li:lt(2)”)2Selects all elements matched by <li> element before the third one; in other words, the first two <li> elements.

$(“p:lt(3)”)2Selects all elements matched by <p> elements before the fourth one; in other words the first three <p> elements.

$(“li:gt(1)”)2 Selects all elements matched by <li>after the second one.

$(“p:gt(2)”)2Selects all element matchen by <p> after the third one.

$(“div/p”)2 Selects all elements matched by <p> that are children of an element matched by<div>

$(“div//code”)2 Selects all elements matched by <code> that are descendants of an element matched by <div>.

$(“//p//a”)2Selects all elements matched by<a> that are descendants of an element matched by <p>

$(“li:first-child)”)2 Selects all elements matched by <li> that are the first child of their parent.

$(“li:last-child)”)2 Selects all elements matched by <li> that are the last child of their parent.

$(“:parent”)2Selects all elements that are the parent of another element ,including text.

$(“li:contains (second)”)2 Selects all elements matched by <li> that contain the text second.

You can use all the above selectors with any HTML/XML element in generic way .For example if selector $(“li:first”) works for <li> element then $ (“p:first”) would also work for <p> element.


Document Ready Function

You might have noticed, that all jQuery methods, in our examples, are inside a document.ready() function

$(document.ready)(ready)(function){

// jQuery functions go here….

});

This is to prevent any jQuery code from running before the document is finished loading(is ready)

Here are some examples of actions that can fail if functions are run before the document is fully loaded :

  • Trying to hide an element that doesn’t exist
  • Trying to get the size of an image that is not loaded

How to use custom Scripts?

It is better to write our custom code in the custom JavaScript file : custom.js, as follows:

/* Filename : custom.js */

$(document).ready(function()) {

$(“div”).click(function()) {

alert(“Hello world!”);

});

});

Now we can include custom.js file in our HTML file as follows :

<html>

<head>

<title> The JqueryExampe</title>

<script type=”text/javascript” src=”/jquery/jquery-1.3.2.min.js”></script>

<script type=”text/javascript” src=”/jquery/custom.js></script>

</head>

<body>

<div id=”newdiv”>

Click on this to see a dialogue box. </div>

</body>

</html>

Using Multiple Libraries

You can use multiple libraries all together without conflicting each others. For example you can use jQuery and MooTooljavaScript libraries together.

JQuery – noConfilct() Method

Many JavaScript libraries use $ as a function or variable name, just as JQuery does. In query’s ease, $ is just an alias for JQuery, so all functionality is available without using $

Run $.noConflict()

method to give control of the $ variable back to whichever library first implemented it. This helps to make sure that jQuery doesn’t conflict with the $ object of other libraries.

Definition and Usage

The noConflict() method releases jQuery’s control of the $ variable

This method can also be used to specify a new custom name for the JQuery variable

Tip :

This method useful when other JavaScript libraries use the $ for their functions.

Syntax

$.noConflict(removeAll)

 

Parameter Description
removeAll optional. A Boolean value that specifies whether or not release jQuery’s control of ALL JQuery variable (including “jQuery”)

 

<html>

<head>

<script type=”text/javascript” src=”jquery.js”></script>

<script type=”text/javascript”>

varjq=$.noconflict();

jq(document).ready(function()) {

jq(“button”).click(function()) {

jq(“p”).hide();

});

});

</script>

</head>

<body>

<h2>This is a heading </h2>

<p>This is a paragraph. </p>

<p>This is another paragraph </p>

<button>click me</button>

</body>

</html>

Here is simple way of avoiding any conflict :
// Import other library

// Import jQuery

$.nonConflict();

JQuery(document).ready(function($)

{

// code that uses jQuery’s $ can follow here.

}};

// Code that uses other library’s $ can follow here.

DOM element


JQuery Call back functions

A call-back function is executed after the current animation is 100% finished.

JQuery Call-back functions

JavaScript statements are execute line by line. However, with animations, the next line of code can be run ever though the animation is not finished .This can create errors.

To prevent this you can create a call-back function.

A call back function is executed after the current animation (effect) is finished.

JQuery call back Example

Typical syntax:$(selector).hide(speed, call back)

The call-back parameter is a function to be executed after the hide effect is completed

Example with Call back

$(“p”),hide(1000.function(){

alert(“The paragraph is now hidden”);

});

Without a callbackparameter, the alert box is displayed before the hide effect is completed.

Example without Call back

$(“p”),hide(1000);

alert(“The paragraph is now hidden”);

JQuery –DOM Attributes

Some of the most basic components we can manipulate when it comes to DOM elements are the properties and attributes assigned to those elements.

Most of these attributes are available through Javascript as DOM node properties. Some of the more common properties are:

className

tagName

id

href

title

rel

src

Consider the following HTML mark-up for an image element:

<img id =”myImage” src=”image.gif” alt=”An image” class=”someclass” title=”This is an image”/>

In this elements mark up ,the tag name is img , and the mark-up for id,src,alt,class, and title represents the element’s attributes, each of which consists of a name and a value.

JQuery gives the means to easily to manipulate an element’s attributes and gives us access to the element so that we can also change its properties.

Get attribute Value

The attr() method can be used to either fetch the value of an attribute from the first element in the matched set pr set attribute values on to all matched elements.

Example

Following is a sample example which fetches title attribute of <em> tag and set <div id =”divid”> value with the same value:

<html>

<head>

<title> the title</title>

<script type=”text/javascrpit” src=”/jquery/jquery-1.3.2.min.js”></script>

$(document).ready(function(){

var title=$(“em”).attr(“title”);

$(“#divid”).tect(title);

});

</script>
</head>

<body>

<div>

<em title =”Bold and Brave”> This is first paragraph.</em>

<p id=”myid”>This is second paragraph</p>

<div id =”divid”></div>

</div>

</body>

</html>

Set Attribute Value

The attr(name,value) method can be used to set the named attribute onto all elements in the wrapped set using the passed value.

Example

Following is a simple example which set src attribute of an image tag to a correct location:

<html>

<head>

<title> The title</title>

<script type=”text/javascript” src=”/jquery/jquery-1.3.2.min.js”></script>

<script type=”text/javascript” language=”javascript”>

$(document).ready(function(){

$(“#myimg”).attr(“src”,”/images/jquery.jgp”);

});

</script>

</head>

<body>

<div><img id=”myimg” src=”/wongpath.jpg” alt=”Sample image”/>

</div>

</body>

</html>


Applying Styles

The addClass(classes) method can be used to apply defined style sheets onto all the matched elements. You can specify multiple classes separated by space.

Example

Following is a sample example which set src attribute of an image tag to a correct location.

<html>

<head>

<title>The title</title>

<script type=”text/javascript” src=”/jquery/jquery-1.3.2.min.js”></script>

<script type=”text/javascript” language=”javascript”>

$(document).ready(function(){

$(“em”).addclass(“selected”);

$(“#myid”).addClass(“highlight”);

});

</script>

<style>

.selected {color:red; }

.highlight{background:yellow;}

</style>

</head>

<body>

<em title=”Bold and Brave”> This is first paragraph.</em>

<p id=”myid”> This is second paragraph.</p>

</body>

</html>

Useful Attribute Methods

Following table lists down few useful methods which you can use to manipulate attributes and properties:

Methods Description
attr(properties) Set a key /value object as properties to all matched elements.
attr(key,fn) Set a single property to a computes value, on all matched elements.
removeAttr(name) Remove an attribute from each of the matched elements.
hasclass(class) Returns true if the specified class is present on at least one of the set of matched elements.
removeClass(class) Removes all or the specified class(es) form the set of matched elements.
toggleClass(class) Adds the specified class if it is not present, removes the specified class if it is present.
html() Get the html contents (innerHTML) of the first matched element
html(val) Set the html contents of every of every matched element.
text() Get the combined text contents of all matched elements.
text(val) Set the text contents of all matched elements.
val() Get the input value of the first matched element
val(val) Set the attribute of every matched element if it is called on <input> but if it is called on <select>  with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box an d radiobox would be checked.

Similar to above syntax and examples, following examples give you understanding on using various attribute methods in different situation

$(“#myID”).attr(“custom”)        2 This would return value of attribute custom for the first element matching with ID myID.

$(“img”).attr(“alt”,”Sample Image”)  2 This sets the alt attribute of all the images to a new value “Sample Image”

$(“input”).attr({value:””,”Sample Image”);   2Sets the value of all <input> elements to the empty string, as well as sets the title to the string please enter a value.

$(“a[href^=http://]”).attr(“target”,”_blank”)    2 selects all links with an href attribute starting with http:// and set its target attribute to _blank

$(“a”).removeAttr(“target”)    2 This would remove target attribute of all the links.

$(“form”).submit(function() { $(“:submit”,this).attr(“disabled”,”disabled”);});   2 This would modify the disabled attribute to the value “disabled” while clicking submit button.

$(“p:last”).hasClass(“selected”)      2 This return true if last <p> tag has associated classselected.

$(“p”).text()  2 Returns string that contains the combined text contents of all matched<p> elements.

$(“p”).text(“<i>Hello World</i>”)   2 this would set “<i>Hello World</I> as text content of the matching <p> elements

$(“p”).html()    2 This returns the HTML content of the all matching paragraphs.

$(“div”).html(“Hello World”)      2 This would set the HTML Content of al matching <div> to Hello world.

$(“input:checkbox:checked”).val()     2Get the first value from a checked checkbox

$(“input:radio[name=bar]:checked”).val()   2Get the first value from a set of radio buttons

$(“button”).val(“Hello”)   2Sets the value attribute of every matched element <button>

$(“input”).val(“on”)       2 This would check all the radio or check box button whose value is “on”.

$(“select”).val(“Orange”)   2This would select Orange option in a dropdown box with options Orange, Mango and Banana.

$(“select”).val(“Orange”,”Mango”)  2 This would select orange and Mango options in a dropdown box with options Orange, Mango and Banana.

JQuery DOM Traversing

JQuery is a very powerful tool which provides a variety of DOM traversal methods to help us select elements in a document randomly as well as in sequential method.

Most of the DOM Traversal Methods do not modify the JQuery object and they are used to filter our elements from a document based on given conditions.

Find Elements by index 

Consider a simple document with the following HTML content.

<html>

<head>

<title>the title</title>

</head>

<body>

<div>

<ul>

<li> List item 1</li>

<li>list item 2</li>

<li>list item 3</li>

<li>list item4 </li>

<li>list item5 </li>

<li>list item6 </li>

</ul>

</div>

</body>

</html>

  • Above every list has list own index, and can be located directly by using eq(index) method as below
  • Every child element starts its index from Zero,thus,list item2 would be accessed by using $(“li”).eq(1) and so on.

Example:

Following is a simple example which adds the color to second item.

<html>

<head>

<title> The title</title>

<script type=”text/javascrpit” src=”/jquery/jquery-1.3.2.min.js></script>

<script type=”text/javascript” language=”javascript”>

$(document).ready(function(){

$(“li”).eq(2).addClass(“selected”);

});

</script>

<style>

.selected{color:red;}

</style>

</head>

<body>

<div>

<ul>

<li> list item 1</li>

<li> list item 2</li>

<li> list item 3</li>

<li> list item 4</li>

<li> list item 5</li>

<li> list item 6</li>

</ul>

</div>

</body>

</html>


jQuery DOM Traversing Methods

Filtering out Elements

The filter(selector) method can be used to filter out all elements from the set of matched elements that do not match the specified selector(s).The selector can be written using any selector syntax.

Example

Following is a simple example which applies color to the lists associated with middle class:

<html>

<head>

<title> The title</title>

<script type=”text/javascript” src=”/jquery/jquery-1.3.2.min.js”></script>

<script type=”text/javascript” language=”javascript”>

$(dcoumnet).ready(function(){

S(“li”).filter(“.middle”).addClass(“selected”);

});

</script>

<Style>

.selected{color:red;}

</style>

</head>

<body>

<ul>

<li class=”top”> list item 1</li>

<li class=”top”> list item 2</li>

<li class=”middle”> list item 3</li>

<li class=”middle”> list item 4</li>

<li class=”bottom”> list item 5</li>

<li class=”bottom”> list item 6</li>

</ul>

</div>

</body>

</html>

Locating Descendant Elements

The find(selector) method can be used to locate all the descendant elements of a particular type of elements.The selector can be written using any selector syntax.

Example

Following is an example which selects all the <span> elements available inside different <p> elements:

<html>

<head>

<title> The title</title>

<script type=”text/javascript” src=”/jquery/jquery-1.3.2.min.js”></script>

<script type=”text/javascript” language=”javascript”>

$(dcoumnet).ready(function(){

S(“p”).find(“span”).addClass(“selected”);

});

</script>

<Style>

.selected{color:red;}

</style>

</head>

<body>

<p>This is 1st paragraph and <span>THIS IS RED</span></p>

<p>This is 2nd paragraph and <span>THIS IS ALSO RED</span></p>

</body>

</html>

JQuery DOM Traversing Methods

Following table lists down useful methods which you can use to filter out various elements from a list of DOM elements:

Selector Description
eq(index) Reduce the set of matched elements to a single element.
tilter(selector) Removes all elements from the set of matched elements that do not match the specified selector(s).
filter(fn) Removes all elements from the set of matched elements that do not match the specified function.
is(selector) Checks the current selection against an expression and returns true,if at least one element of the selection fits the given selector.
map(callback) Translate asset of elements in the jQuery object into another set of values in a jQuery array(which may ,or may not contain elements).
not (selector) Removes elements matching the specified selector from the set of matched elements.
slice(start,[end]) Selects a subset of the matched elements.

Following table lists down other useful methods which you can use to locate various elements in a DOM

Selector Description
add(selector) Adds more elements, matched by the given selector, to the set of matched elements.
andSelf() Add the previous selection to the current selection
children([selector]) Get a set of elements containing all of the unique immediate children of each of the matched set of elements.
closest(selector) Get a set of elements containing the closest parent element that matches the specified selector, the starting element included.
contents() Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.
end() Revert the most recent ‘destructive’ operation, changing the set of matched elements to its previous state.
find(selector) Searches for descendent elements that match the specified selectors.
next([selector]) Get a set of elements containing the unique next siblings of each of the given set of elements.
nextAll([selector]) Find all sibling elements after the current element.
offsetParent() Returns a jQuery collection with the positioned parent of the first matched element.
parent([selector]) Get the direct parent of an element. If called on asset of elements, parent returns a set of their unique direct parent elements.
parents([selector]) Get a set of elements containing the unique ancestors of the matched set of elements(except for the root element).
prev([selector]) Get a set of elements containing the unique previous siblings of each of the matched set of elements.
prevAll([selector]) Find all sibling elements in front of the current element.
siblings([selector]) Get a set of elements containing all of the unique siblings of each of the matched set of elements.

jQuery CSS  Methods

The  jQuery library supports nearly all of the selectors included in Cascading Style Sheet(CSS) specifications I through 3, as outlined on the world wide web consortium’s site.

Using JQuery library developers can enhance their websites without worrying about browsers and their versions as long as the browsers have JavaScript enabled.

Most of the JQuery CSS Methods do not modify the content of the jQuery object and they are used to apply CSS properties on DOM elements.

 

Apply CSS Properties 

This is very simple to apply any CSS property using JQuery method css(PropertyName, Property value)

Here is the syntax for the method.

selector.css(PropertyName, PropertyValue);

Here you can pass PropertyName as a JavaScript string based on its value, PropertyValue could be string or integer.

Example

Following is an example which adds font color to the second list item.

<html>

<head>

<title>the title</title>

<script type=”text/javascript” src=”/jquery/jquery-1.3.2.min.js”></script>

<script type=”text/javascript” language=”javascript”>

$(document).ready(function()) {

$(“li”).eq(2).css(“color”,”red”);

});

</script>

</head>

<body>

<div>

<ul>

<li>list item 1</li>

<li>list item 2</li>

<li>list item 3</li>

<li>list item 4</li>

<li>list item 5</li>

<li>list item 6</li>

</ul>

</div>

</body>

</html>


jQuery DOM Manipulation Methods

jQuery provides methods to manipulate DOM efficient way. You do not need to write big code to modify the value of any element’s attribute or to extract HTML code from a paragraph or division.

jQuery provides methods such as .attr(),.html(), and .val() which act as getters, retrieving information from DOM elements for later use.

jQuery Content Manipulation

The html()  method gets the html contents (inner HTML) of the first matched element.

Here is the syntax for the method.

selector.html()

Example

Following is an example which makes use of .html()  and .text(val) methods. Here .html() retrieves HTML content form the object and then .text(val) method sets value of the object using passed parameter.

<html>

<head>

<title>the title</title>

<script type=”type/javascript” src=”/jquery/jquery-1.3.2.min.js”></script>

<script type=”text/javascript” language=”javascript”>

$(document). ready(function()) {

$(“div”).click(function()) {

var content = $(this).html();

$(“#result”).text(content);

}};

}};

</script>

<style>

#division { margin : 10px;padding : 12px;

border:2 px solid # 666;

width:60px;

}

</style>

</head>

<body>

<p> click on the square below:< /p>

<span id=”result”> </span>

<div id=”division” style=”background-color:blue;”>

This is blue square!!

</div>

</body>

</html>

DOM Element Replacement

You can replace a complete DOM element with the specified HTML or DOM elements. The replace with(content) method serves this purpose very well.

Here is the syntax for the method.

selector.replacewith(.content)

Here content is what you want to have instead of original element. This could HTML or simple text.

Example

<html>

<head>

<title>the title</title>

<script type=”type/javascript” src=”/jquery/jquery-1.3.2.min.js”></script>

<script type=”text/javascript” language=”javascript”>

$(document). ready(function()) {

$(“div”).click(function()) {

$(this).replacewith(“<h1>jQuery is great</h1>”);

});

});

</script>

</script>

<style>

#division { margin : 10px;padding : 12px;

border:2 px solid # 666;

width:60px;

}

</style>

</head>

<body>

<p> click on the square below:< /p>

<span id=”result”> </span>

<div id=”division” style=”background-color:blue;”>

This is blue square!!

</div>

</body>

</html>

Removing DOM Elements

There may be a situation when you would like to remove one or more DOM element s form the document.jQuery provides two methods to handle the situation.

The empty() method remove all child nodes from the set of matched elements where as the method remove(expr) method removes all matched elements from the DOM.

Here is the syntax for the method.

selector.remove([expr])

or

selector.empty()

You can pass optional parameter expr to filter the set of elements to be removed.

Example 

Following is an example where elements are being removed as soon as they are clicked:

<html>

<head>

<title>the title</title>

<script type=”type/javascript” src=”/jquery/jquery-1.3.2.min.js”></script>

<script type=”text/javascript” language=”javascript”>

$(document). ready(function()) {

$(“div”).click(function()) {

$(this).remove();

});

});

</script>

<style>

.div { margin : 10px;padding : 12px;

border:2 px solid # 666;

width:60px;

}

</style>

</head>

<body>

<p> click on the square below:< /p>

<span id=”result”> </span>

<div class=”div” style=”background-color:blue;”></div>

<div class=”div” style=”background-color:green;”></div>

<div class=”div” style=”background-color:red;”>

</div>

</body>

</html>

Inserting DOM elements

There may be a situation when you would like to insert new one or more DOM elements in your existing document. jQuery provides various methods to insert elements at various locations.

The after(content) method insert content after each of the matched elements where as the method before(content) method inserts content before each of the matched elements.

Here is the syntax for the method:

selector.after(content)

or

selector.before(content)

Here content is what you want to insert. This could be HTML or simple text.

Example 

Following is an example where <div> elements are being inserted just before the clicked element :

<html>

<head>

<title>the title</title>

<script type=”type/javascript” src=”/jquery/jquery-1.3.2.min.js”></script>

<script type=”text/javascript” language=”javascript”>

$(document). ready(function()) {

$(“div”).click(function()) {

$(this).before(‘<div class=”div”></div>’);

});

});

</script>

<style>

.div { margin : 10px;padding : 12px;

border:2 px solid # 666;

width:60px;

}

</style>

</head>

<body>

<p> click on the square below:< /p>

<span id=”result”> </span>

<div class=”div” style=”background-color:blue;”></div>

<div class=”div” style=”background-color:green;”></div>

<div class=”div” style=”background-color:red;”>

</body>

</html>

DOM Manipulation Methods

Following table lists down all the methods which you can use to manipulate DOM elements

Method Description
after(content) Insert content after-each of the matched elements.
append(content) Append content to the inside of every matched element.
appendTo(selector) Append all of the matched elements to another, specified , set of elements
before(content) Insert content before each of the matched elements
clone(bool) Clone matched DOM elements and all their event handlers, and select the clones.
clone() Clone matched DOM elements and select the clones.
empty() Remove all child nodes from the set of matched elements.
html(val) Set the html contents of every matched element
html() Get the html contents(inner HTML) of the first matched element.
insertAfter(sector) Insert all of the matched elements after another, specified , set of elements.
insertBefore(selector) Insert all of the matched elements before another, specified, set of elements.
prepend(content) Prepend content to the inside of every matched element.
prependTo(selector) Prepend all of the matched elements to another, specified, set of elements.
remove(expr) Removes all matched elements from the DOM.
replaceAll(selector) Replaces the elements matched by the specified selector with the matched elements.
replacewith(content) Replaces all matched elements with the specified HTML or DOM elements
text(val) Set the text contents of all matched elements.
text() Get the combined text contents of all matched elements.
wrap(elem) Wrap each matched element with the specified element.
wrap(elem) Wrap all the elements in the matched set into a single wrapper element.
wrapAll(html) Wrap all the elements in the matched set into a single wrapper element.
wrapinner(elem) Wrap the inner child contents of each matched element(including text nodes) with a DOM element.
wrapinner(html) Wrap the inner child contents of each matched element (including text nodes) with an HTML structure.

CSS Properties in jQuery

Apply Multiple CSS Properties

You can apply multiple CSS properties using a single JQuery method CSS({key 1:val1,key2:val2….) You can apply as many properties as you like in a single call.

Here is the syntax for the method :

selector.css{(key1:val1, key2:val2….KeyN:valN)}

Here you can pass key as property and val as its value as described above.

Example

Following is an example which adds font color as well as background color to the second list item.

<html>

<head>

<title>the title</title>

<script type=”text/javascript” src=”/jquery/jquery-1.3.2.min.js”></script>

<script type=”text/javascript” language=”javascript”>

$(document).ready(function()) {

$(“li”).eq(2).css({“color”,”red”,”background-color” : “green”});

});

</script>

</head>

<body>

<div>

<ul>

<li>list item 1</li>

<li>list item 2</li>

<li>list item 3</li>

<li>list item 4</li>

<li>list item 5</li>

<li>list item 6</li>

</ul>

</div>

</body>

</html>

Setting Element Width & Height

The width(val) and height(val) method can be used to set the width  and height respectively of any element.

Example

Following is a simple example which sets the width of first division element where as rest of the element have width set by style sheet:

<html>

<head>

<title>the title</title>

<script type=”text/javascript” src=”/jquery/jquery-1.3.2.min.js”></script>

<script type=”text/javascript” language=”javascript”>

$(document).ready(function()) {

$(“div:first”).width(100);

$(“div:first”).css(“background-color”,”blue”)

});

</script>

<style>

div{ width:70px; height:50 px;float:left;margin:5px; background:red; cursor:pointer;}

</style>

</head>

<body>

<div></div>

<div></div>

<div>d</div>

<div>d</div>

<div>d</div>

<div>d</div>

</body>

</html>

Jquery CSS Methods

Following table lists down all the methods which you can use to play with CSS properties

Method Description
css(name) Returns a style property on the first matched element.
css(name,value) Set a single style property to a value on all matched elements.
css(properties) Set a key/value object as style properties to all matched elements
height(val) Set the CSS height of every matched element
height() Get the current computed, pixel,height of the first matched element
innerHeight() Gets the inner height(excludes the border and includes the padding ) for the first matched element.
innerwidth() Gets the inner width(excludes the border and includes the padding) for the first matched element
offset() Get the current offset of the first matched element, in pixels, relative to the document
offsetParent() Returns a jQuery collection with the positioned parent of the first matched element
outerWidth([margin]) Get the outer width(includes the border and padding by default) for the first matched element
position() Gets the top and left position of an element relative to its offset parent.
scrollLeft(val) When a value is passed in, the scroll left offset is set to that value on all matched elements.
scrollLeft() Gets the scroll left offset of the first matched element.
scrollTop(val) When a value is passed in, the scroll top offset is set to that value on all matched elements.
scrollTop() Gets the scroll top offset of the first matched element.
width(val) Set the CSS width of every matched element.
width() Get the current computed, pixel, width of the first matched element.

Event Handling in jQuery

We have the ability to create dynamic web pages by using events. Events are actions that can be detected by your web application.

Following are the examples events :

A mouse click

A Web page loading

Taking mouse over an element

Submitting an HTML form

A keystroke on your keyboard

When these events are triggered you can then use a custom function to do pretty much whatever you want with the event. These custom functions call Event Handlers.

Binding Event Handlers

Using the jQuery Event Model, we can establish event handlers on DOM elements with the bind() method as follows:

$(‘div’).bind(‘click’,function(event)

{

alert(‘Hi there!’);

});

This code will cause the division element to respond to the click event; when a user clicks inside this division thereafter, the alert will be shown.

The full syntax of the bind() command is as follows:

selector.bind(evenType[, evenData], handler)

Following is the description of the parameters:

EvenType

A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.

EventData

This is optional parameter is a map of data that will be passed to the event handler.

Handler

A function to execute each time the event is triggered.

Removing Event Handlers

Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler.

jQuery provides the unbind() command to remove an existing event handler. The syntax of unbind() is as follows :

selector.unbind(eventType, handler)

or

selector.unbind(eventType)

Following is the description of the parameters

eventType: 

  • A string containing a JavaScript listener that.s to be removed.

Event Types

The following are cross platform and recommended event types which you can bind using jQuery

Event Type                         Description
blur Occurs when the element loses focus
change Occurs when the element changes
click Occurs when a mouse click
dbclick occurs when a mouse double-click
error Occurs when there is an error in loading or unloading etc.
focus Occurs when the element gets focus.
keydown Occurs when key is pressed
keypress Occurs when key is pressed and released.
keyup Occurs when key is released
load Occurs when document is loaded
mousedown Occurs when mouse button is pressed
mouseenter Occurs when mouse enters in an element region
mouseleave Occurs when mouse leaves an element region
mousemove Occurs when mouse pointer moves
mouseout Occurs when mouse pointer moves out of an element
mouseover Occurs when mouse pointer moves over an element
mouseup Occurs when mouse button is released
resize Occurs when window is resized
scroll Occurs when window is scrolled
select occurs when a text is selected
submit Occurs when form is submitted
unload Occurs when documents is unloaded

The Event Object

The callback function takes a single parameter, when the handler is called the JavaScript event object will be passed through it.

The event object is often unnecessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered. However there are certail attributes which you would need to be accessed.

The Event Attributes

The following event properties/attributes are available and safe to access in a platform independent manner.

Property                             Description
altkey Set to true if the Alt key was pressed when the event was triggered, false if not. The Alt key is labeled option on most Mac keyboards.
ctrlKey Set to true if the ctrl key was pressed when the event was triggered, false if not.
data The value, if any, passed as the second parameter to the blind() command when the handler was established.
keycode For keyup and keydown events, this returns the key that was pressed.
metakey Set to true if the Meta key was pressed when the event was triggered, false if not. The Meta key is the ctrl key on PCs and the command key on Macs.
pageX For mouse events, specifies the horizontal coordinate of the event relative for the page origin
pageY For mouse events, specifies the vertical coordinate of the event relative from the page origin.
relatedTarget For some mouse events, identifies the element that the cursor left or entered when the event was triggered.
screen For mouse events, specifies the horizontal coordinate of the event relative from the screen origin.
screen Y For mouse events, specifies the vertical coordinate of the event relative from the screen origin
shiftkey set to true if the shift key was pressed when the event was triggered , false if not.
target Identifies the elment for which the event was triggered.
timestamp The timestamp(in milliseconds) when the event was created.
type For all events, specifies the type of event that was triggered(for example,click)
which For keyboard events, specifies the numeric code for the key that caused the event, and for mouse event, specifies which button was pressed (1 for left,2 for middle, 3 for right)

Event Helper Methods

jQuery also provides a set of event helper functions which can be used either to trigger an event to bind any event types mentioned above.

Trigger Methods

Following is an example which would triggers the blur event on all paragraphs:

$(“p”).blur();

Binding Methods in jQuery

Following is an example which would bind a click event on all the <div>:

$(“div”).click(function()) {

// do something here

{);

Here is a complete list of all the support methods provided by jQuery

Method Description
blur() Triggers the blur event of each matched element.
blur(fn) Bind a function to the blur event of each matched element.
change() Triggers the change event of each matched element.
change(fn) Binds a function to the change event of each matched element.
click() Triggers the click event of each matched element.
click(fn) Binds a function to the click event of each matched element.
dbclick() Triggers the dbclick event of each matched element.
error() Triggers the error event of each matched element.
error(fn) Binds a function to the error event of each matched element.
focus() Triggers the focus event of each matched element.
focus(fn) Binds a function to the focus event of each of each matched element
keydown() Triggers the keydown event of each matched element.
keydown(fn) Bind a function to the keydown event of each matched element.
Keypress() Triggers the keypress event of each matched element.
keypress(fn) Binds a function to the keypress event of each matched element.
keyup() Triggers the keyup event of each matched element.
keyup(fn) Bind a function to the keyup event of each matched element.
load(fn) Binds a function to the load event of each matched element.
mouseenter(fn) Bind a function to the mouseenter event of each matched element.
mouseleave(fn) Bind a function to the mouseleave event of each matched element.
mousemove(fn) Bind a function to the mousemove event of each matched element.
mouseout(fn) Bind a function to the mouseout event of each matched element
mouseover(fn) Bind a function to the mouseover event of each matched element.
mouseup(fn) Bind a function to the mouseup event of each matched element.
resize(fn) Bind a function to the resize event of each matched element.
scroll(fn) Bind a function to the scroll event of each matched element.
select() Trigger the select event of each matched element
select(fn) Bind a function to the select event of each matched element.
submit() Trigger the submit event of each matched element.
submit(fn) Bind a function to the submit event of each matched element
unload(fn) Binds a function to the unload event of each matched element.

Handling Events using JavaScript

Question :What type of JavaScript code do you write to handle a button click event?

Answer  

It depends on the browser!

Event Attachment Techniques

Most Browsers

mybutton.addEventListerer(‘click’,function() {}, false);

Internet Explorer

mybutton.attachment(‘onclick’,function() { });

jQuery Event Model Benefits

Events notify a program that a user performed some type of action

jQuery provides a cross-browser event model that works in IE, Chrome, Opera, Firefox, Safari and more

jQuery event model is simple to use and provides a compact syntax

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

</head>

<body>

<button id=”buttonId”> click</button>

<script type=”text/javascript”>

var myButton=document.getElementById(“buttonId”);

if(document.addEventListener) {

myButton.addEventListener(“click”,function()) {alert(“click Button”);},false);

}else{

mybutton.attachEvent(“onclick”,function(){alert(“click IE Button”);});

}

</script>

</body>

</html>

Handling Click Events

Raising a click event from within another function:

$(‘#otherID’).click(function() {

$(‘#myID’).click();

});

This would fire when the element otherID was clicked and raise the click event for myID

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

$(document).ready(function() {

$(‘#buttonid1’).click(function() {

// raising the event using jQuery function

alert(“button1 is clicked”);

$(“#buttonld2”).click();

});

$(“#buttonid2”).click(function() {

alert(“button2 is clicked”);

});

});

</script>

</head>

<body>

<button id=”buttonid1”> click</button>

<button id=”buttonid2”> click2</button>

</body>

</html>

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function() {

alert(“City Dropdown changed to :” + $(this).val());

});

});

</script>

</head>

<body>

<select id=”cityId”>

<option value=”hyd”>Hyderabad</option>

<option value=”hyd”>Hyderabad</option>

<option value=”bang”>Banglore</option>

<option value=”mumbai”>Mumbai</option>

<option value=”hyd”>Hyderabad</option>

</select>

</body>

</html>

Handling Click Events

click(handler(eventObject)) is used to listen for a click event or trigger a click event on an element

$(‘#myID’).click(function() {

alert(‘The element myID was clicked’);

});

<html>

<head>

<script type=”text/css”>

.Hilight:

bigground-color:pink;

}

</style>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javacript”>

$(document).ready(function(){

$(“div#myDiv”).click(function(event) {

$(this).addClass(“Hilight”);

var result=””;

result=result+”x:”+event.pageX+”<br/>”;

result=result+”Y:”+event.pageY+”<br/>”;

result=result+”keycode:”+event.keycode+”<br/>”;

result=result+”TimeStamp:” + event.timeStamp+”<br/>”;

result=result+”Target element ID:”+$(event.target).attr(“id”)+”<br/>”;

result=result+”Event type:” + event.type+”<br/>”;

$(this).html(result);

});

});

</sript>

</head>

<body>

<div id=”myDiv” style=”width:400px;height:200px;border:2px solid black;”>

This is my div

This is my div

This is my div

This is my div

</div>

</body>

</html>

<html>

<head>

<script type=”text/css”>

.Hilight:

bigground-color:pink;

}

</style>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javacript”>

$(document).ready(function(){

$(“div#myDiv”).mouseenter(function() {

$(this).toggleclass(“Hilight”);

}).mouseleave(function(){

$(this).toggleclass(“Hilight”);

}}.click(function(event){

$(this).text(“X: “+event.pageX+”Y:”+event.pageY);

}};

}};

</sript>

</head>

<body>

<div id=”myDiv” style=”width:400px;height:200px;border:2px solid black;”>

This is my div

This is my div

This is my div

This is my div

This is my div

</div>

</body>

</html>

Using bind()

.bind(eventType,handler(eventObject)) attaches a handler to an event for the selected element(s)

$(‘#MyDiv’).bind(‘click’,function()) {

//Handle click event

});

.click() is the same as .bind(‘click’)

Using unbind()

unbind(event) is used to remove a handler previously bound to an element:

$(‘#test’).click(handler); can be unbound using

$(‘#text’).unbind();

Specific events can also be targeted using unbind():

$(‘#test’).unbind(‘click’);

Binding Multiple Events using jQuery

bind() allows multiple events to be bound to one or more elements

Event names to bind are separated with a space:

$(‘#MyDiv’).bind(‘mouseenter mouseleave’,

function()

{

$(this).toggleclass(‘entered’);

}

);

 

<html>

<head>

<script type=”text/css”>

.Hilight:

bigground-color:pink;

}

</style>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javacript”>

$(document).ready(function(){

$(“div#myDiv”).bind(“mouseenter mouseleave click”,function(event) {

$(this).toggleClass(“Hilight”);

if(envetscope==’click’){

$(this).add(“X:” + even.pageX+”Y:”+event.pageY);

}

});

$(“button”).click function(){

//$(“divmyDiv”).unbind();

$(“div#.Div”).unbind(“click”);

}};

});

</sript>

</head>

<body>

<div id=”myDiv” style=”width:400px;height:200px;border:2px solid black;”>

This is my div

This is my div

This is my div

This is my div

This is my div

</div>

<button>Unbind even button</button>

</body>

</html>

live() and delegate() Functions

  • live() and delegate() allow new elements added into the DOM automatically be “attached” to an event handler

live() – Allow binding of event handlers to elements that match selector, including future elements. Events bubble upto the document object.

delegate() – Replacement for live() in jQuery 1.4

Attaches an event handler directly to the selector context.

Using live()

  • Event handlers can be set using live()
  • The document object handles events by default
  • Works even when new objects are added into the DOM:

$(‘.someclass’).live(‘click’,someFunction);

Stop live event handling using die();

$(‘.someClass’).die(‘click’,someFunction);

Screenshot_10

Click Event

<spanclass=”someclass”/>

<p class=”someclass”/>

<div class=”someClass”/>

Using delegate()

Newer version of live() added in jQuery 1.4

A context object (#Divs in the sample belpw) handles events by default rather than the document object

Works even when new objects are added into the DOM:

$(‘#Divs’).delegate(‘div’,’click’,someFunction);

Stop delegate event handling using undelegate()

How delegate() works

Screenshot_11

Click Event

<span class=”someclass”/>

<p class=”someClass”/>

<div class=”someclass”/>

<html>

<head>

<script type=”text/javascript”src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function(){

var PhoneDiv=$(“div#newDiv”);

$(“#AddPhoneButton”,click(function(){

var phoneType.Clone=$(“div:eq(0)”.PhoneDiv).clone();

var PhoneNumber.Divclone=$(“div:eq(1)”,PhoneDiv).clone();

$(“select”,phone.typeDivclone).val(“);

$(“input”,phone.NumberDivclone).val(‘’)l

PhoneDiv.apper(“<div style=’clear:both’/>”.append(PhoneTypeDivcloappend(PhoneNumberDivclone)));

$(“input”,PhoneDiv).keypress”,function(event){

if(event.keycode(48) || event.keycode>57){

//even propagation();

return;

}

}};

$(“button”).click(function) {

// $(“input”,phoneDiv).die();

$(“input”,Phonediv).die(“keypress”);

});

PhoneDiv.delegate(“im”,”keypress”,function(event){

if(event.keycode 48 || event.keycode>57){

//even popPropagatation();

return;

}

}0;

$(“button”).click(function){

PhoneDiv.undelegate(“input”,”keypress”);

}};

}};

</script>

</head>

<body>

<table boarder=”1”>

<tr>

<td>Name</td>

<td>

<input type=”text”,name=”name”/>

</td>

</tr>

<tr>

<td> Password </td>

<td>

<input type=”password” name=”password” />

</td>

</tr>

<tr>

<td> Address</td>

<td>

<textarea cols=”50” rows=”4”></textarea>

</td>

</tr>

<tr>

<td>Phone</td>

<td>

<input type=”submit” id=”AddPhoneButton” value=”AddPhone”/>

<div id=”PhoneDiv”>

<div id=”PhoneTypeDiv” style=”float:left”>

<select name=”PhoneType”>

<option value=””>Select One</option>

<option value=”Mobile”>Mobile</option>

<option value=”Office”>Office</option>

<option value=”Home”>Home</option>

</select>

</div>

<div id=”PhoneNumberDiv” style=”float:left”>

<input type=”text” name=”PhoneNumber”/>

</div>

</div>

</td>

</tr>

<tr>

<td>City</td>

<td>

<select id=”cityID”>

<option value=”hyd”>Hyderabad</option>

<option value=”bang”>Banglore</option>

<option value=”chennai”>chennai</option>

<option value=”mumbai”>Mumbai</option>

</select>

</td>

</tr>

<tr>

<td colspan=”2” align=”center”>

<input type=”submit” value=”submit”/>

</td>

</tr>

</table>

<button>Release Event Handlers</button>

</body>

</html>


Handling Hover Events in jQuery

Hover events can be handled using hover():

$(selector).hover(handlerIn,handlerout)

handlerIn is equivalent to mouseenter and handler out is equivalent to mouseleave

 Using hover()

This example highlights #target on mouseenter and sets it back to white on mouseleave.

$(‘#target’).hover(

function(){

$(this).css(‘background color’,’#00FF99’);

};

function(){

$(this).css(‘background-color’,’#FFFFFF’);

}

);

Alternate Hover Example

Another option is $(selector).hover(handlerInOut)

Fires the same handler for mouseenter and mouseleave events

Used with jQuery’s toggle methods:

$(‘p’).hover(function() {

$(this).toggleclass(‘over’);

});

This code will toggle the class applied to a paragraph element

<html>

<head>

<style type=”text/css”>

.Hilight{

background-color:#efefef;

}

</style>

<script type=”text/javascript” src=”jquery.js”></script>

<script type=”text/javascript”>

$(document).ready(function() {

/*

$(“table#MyTable tr”).hover(

function(){

//mouseenter

$(this).css(“background-color”,”#efefef”);

};

function(){

//mouseleave

$(this).css(“background-color”,”#ffffff”);

}

};

*/

$(“table#Mytable tr”).hover(function() {

$(this).toggleclass(“Hilight”);

}};

});

</script>

</head>

<body>

<table id=”MyTable” border=”1”>

<tr>

<th>ENO</th>

<th>Name</th>

<th>Sal</th>

</tr>

<tr>

<td>1001</td>

<td>sekhar1</td>

<td>459.09</td>

</tr>

<tr>

<td>1002</td>

<td>sekhar2</td>

<td>459.09</td>

</tr>

<tr>

<td>1003</td>

<td>sekhar3</td>

<td>459.09</td>

</tr>

<tr>

<td>1004</td>

<td>sekhar4</td>

<td>459.09</td>

</tr>

<tr>

<td>1005</td>

<td>sekhar5</td>

<td>459.09</td>

</tr>

</table>

</body>

</html>

<html>

<head>

<style type=”text/css”>

.Hilight{

background-color:#efefef;

}

</style>

<script type=”text/javascript” src=”jquery.js”></script>

<script type=”text/javascript”>

$(document).ready(function() {

$(“table#MyTable tr”).toggle(

function(){

//click

$(this).css(“background-color”,”#efefef”);

};

function(){

//click

$(this).css(“background-color”,”purple”);

};

function(){

//click

$(this).css(“background-color”,”yellow”);

};

function() {

//click

$(this).css(“background-color”,”pink”);

}

};

}};

</script>

</head>

<body>

<table id=”MyTable” border=”1”>

<tr>

<th>ENO</th>

<th>Name</th>

<th>Sal</th>

</tr>

<tr>

<td>1001</td>

<td>sekhar1</td>

<td>459.09</td>

</tr>

<tr>

<td>1002</td>

<td>sekhar2</td>

<td>459.09</td>

</tr>

<tr>

<td>1003</td>

<td>sekhar3</td>

<td>459.09</td>

</tr>

<tr>

<td>1004</td>

<td>sekhar4</td>

<td>459.09</td>

</tr>

<tr>

<td>1005</td>

<td>sekhar5</td>

<td>459.09</td>

</tr>

</table>

</body>

</html>


jQuery Effects

jQuery provides a trivially simple interface for doing various kind of amazing effects jQuery methods allow us to quickly apply commonly used effects with a minimum configuration.

jQuery Effect Methods

You have seen basic concept of jQuery Effects. Following table lists down all the important methods to create different kind of effects:

jQuery Hide and Show

With jQuery, you can hide and show HTML elements with the hide() and show() methods

Example

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function(){

$(“#hide”).click(function() {

$(“p”).hide();

});

$(“#show”).click(function(){

$(“p”).show();

}};

});

</script>

</head>

<body>

<p>if you click on the “Hide” button, i will disappear</p>

<button id =”hide”>Hide</button>

<button id=”show”>Show</button>

</body>

</html>

Both hide() and show() can take two optional : speed and call back.

Syntax 

$(selector).hide(speed ,call-back)

$(selector).show(speed, call-back)

The speed parameter specifies the speed of the hiding / showing and can take the following values:”slow”, ”fast”,” normal”, or  milliseconds

Example 

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function(){

$(“#hide”).click(function() {

$(“p”).hide(1000);

});

}};

</script>

</head>

<body>

<p>This is a paragraph with little content</p>

<p>This is another small paragraph.</p>

</body>

</html>

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function(){

$(“.ex.hide”).click(function() {

$(this).parents(“.ex”).hide(“slow”);

}};

}};

</script>

<style type=”text/css”>

div.ex

{

background-color:#e5eecc;

padding:7px;

border:solid 1px #c3c3c3;

}

</style>

</head>

<body>

<h3>Island Trading</h3>

<div class=”ex”>

<button class=”hide”> Hide me</button>

<p>Contact:Helen Bennett<br/>

Garden House Crowther Way<br/>

London</p>

</div>

<h3>Paris specialities</h3>

<div class=”ex”>

<button class=”hide”>Hide me</button>

<p>Contact:Marie Bertrand<br/>

265,Boulevard Charonne<br/>

paris</p>

</div>

</body>

</html>

<p>if you click on the “Hide” button, i will disappear</p>

<button id =”hide”>Hide</button>

<button id=”show”>Show</button>

</body>

</html>

The call-back parameter is the name of a function to be executed after the hide(or show) function completes.

jQuery Toggle

The jQuery toggle() method toggles the visibility of HTML elements using the show() or hide() methods. Shown elements are hidden and hidden elements are shown.

syntax

$(selector).toggle(speed, call-back)

The speed parameter can take the following values: “slow”,” fast”,” normal”, or milliseconds.

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function(){

$(“#hide”).click(function() {

$(“p”).toggle();

}};

}};

</script>

</head>

<body>

<button>Toggle</button>

<p>This is a paragraph with little content</p>

<p>This is another small paragraph.</p>

</body>

</html>

The call-back parameter is the name of a function to be executed after the hide(or show) method completes.

jQuery Slide – slideDown , slide Up, slideToggle

The jQuery slide methods gradually change the height for selected elements.

jQuery has the following slide methods :

$(selector).slideDown(speed,callback)

$(selector).slideUp(speed,callback)

$(selector).slideToggle(spped,callback)

The speed parameter can take the following values” “slow” , “fast”, “normal”, or milliseconds.

The callback parameter is the name of a function to be executed after the function completes.

SlideDown() Example

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function(){

$(“.flip”).click(function() {

$(“.panel”).slideDown(“slow”);

});

</script>

<style type=”text/css”>

div.panel.p.flip

{

margin:0px;

padding:5px;

text-align:center;

background:#e5eecc;

border:solid 1px #c3c3c3;

}

div.panel

{

height:120px;

display:none;

}

</style>

</head>

<body>

<div class=”panel”>

<p>Because time is valuable, we deliver quick and easy learning</p>

<p> At w3schools,you can study everything you need to learn, in an accessible and handy format.</p>

</div>

<p class=”flip”>Show Panel</p>

</body>

</html>

slideUp() Example

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function(){

$(“.flip”).click(function() {

$(“.panel”).slideup(“slow”);

}};

}};

</script>

<style type=”text/css”>

div.panel.p.flip

{

margin:0px;

padding:5pxl

text-align:center;

background:#e5eecc;

border:solid 1px #c3c3c3;

}

div.panel

{

height:120px;

}

</style>

</head>

<body>

<div class=”panel”>

<p>Because time is valuabe, we deliver quick and easy learning</p>

<p> At w3shools, you can study everything you need to learn,in an accessible and handy format. </p>

</div>

<p class = “flip”> Hide Panel</p>

</body>

</html>

 

slide Toggle() Example

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function(){

$(“.flip”).click(function() {

$(“panel”).slideToggle(“slow”);

}};

}};

</script>

<style type=”text/css”>

div.panel,p.flip

{

margin:0px;

padding:5pxl

text-align:center;

background:#e5eecc;

border:solid 1px #c3c3c3;

}

div.panel

{

height:120px;

display:none;

}

</style>

</head>

<body>

<div class=”panel”>

<p>Because time is valuabe, we deliver quick and easy learning</p>

<p> At w3shools, you can study everything you need to learn,in an accessible and handy format. </p>

</div>

<p class = “flip”> Hide Panel</p>

</body>

</html>

jQuery Fade – fadeIn, fadeout, fadeTo

The jQuery fade methods gradually change the opacity for selected elements.

jQuery has the following fade methods

$(selector).fadeIn(speed,callback)

$(selector).fadeOut(speed,callback)

$(selector).fadeTo(speed,opticity,callback)

The speed parameter can take the following values : “slow”, “fast”, “normal”, or milliseconds.

The opacity parameter in the fadeTo() method allows fading a given opacity.

The callback parameter is the name of a function to be executed after the function completes.

fadeTo() Example

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function(){

$(“button”).click(function() {

$(“div”).fadeTo(“slow”,0.25);

}};

}};

</script>

</head>

<body>

<div style=”background:yellow;width:300px;height:300px”>

<button>Click to Fade </button>

</div>

</body>

</html>

fadeout() Example

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function(){

$(“button”).click(function() {

$(“div”).fadeOut(4000);

}};

}};

</script>

</head>

<body>

<div style=”background:yellow;width:200px”>CLICK ME AWAY!</div>

<p>If you click on the box above, it will be removed.</p>

</body>

</html>


jQuery Custom Animations

The syntax of jQuery’s method for making custom animations is:

$(selector).animate({params},[duration],[easing],[call-back])

The key parameter is params , it defines the CSS properties that will be animated. Many properties can be animated at the same time:

animate({width:”70%”.opacity:0.4,marginLeft:”0.6in”,fontsize:”3em”});

The second parameter is duration. It specifies the speed of the animation. Possible values are “fast”,”slow”,”normal”,or milliseconds.

Example 

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function(){

$(“button”).click(function() {

$(“div”).animate({height:300},”slow”);

$(“div”).animate({width:300},”slow”);

$(“div”).animate({height:100},”slow”);

$(“div”).animate({width:100},”slow”);

}};

}};

</script>

</head>

<body>

<button>Start Animation</button>

<br/><br/>

<div style=”background:#98bf21;width:100px;height:100px;position:relative”>

</div>

</body>

</html>

Example 

<html>

<head>

<script type=”text/javascript” src=”jQuery.js”></script>

<script type=”text/javascript”>

$(document).ready(function(){

$(“button”).click(function() {

$(“div”).animate({left:100px},”slow”);

$(“div”).animate({fontsize:”3em”},”slow”);

}};

}};

</script>

</head>

<body>

<button>Start Animation</button>

<br/><br/>

<div style=”background:#98bf21;width:200px;height:100px;position:relative”>HELLOM</div>

</body>

</html>

Note

HTML elements are positioned static by default and cannot be moved. To make elements moveable, set the CSS position property to fixed, relative or absolute.


jQuery Methods

animate(params,[duration,easing,callback])

A function for making custom animations.

fadein(speed,[callback])

Fade in all matched elements by adjusting their opacity and firing an optional call-back after completion.

fadeout(speed,[call-back])

Fade out all matched elements by adjusting their opacity to 0, then setting to “none” and firing an optional call-back after completion.

fadeTo(speed,opacity,callback)

Fade the opacity of all matched elements to a specified opacity and firing an optional call-back after completion.

hide()                  

Hides each of the set of matched elements if they are shown.

hide(speed.[call back])

Hide all matched elements using a graceful animation and firing an optional call-back after completion.

Show()

Displays each of the set of matched elements if they are hidden.

show(speed,[call back])

Show all matched elements using a graceful animation and firing an optional callback after completion.

slideDown(speed,[callback])

Reveal all matched elements by adjusting their height and firing an optional call back after completion.

slideToggle(speed,[call back])

Toggle the visibility of all matched elements by adjusting their height  and firing an optional call-back after completion.

slideUp(speed,[call-back])

Hide all matched elements by adjusting their height and firing an optional call back after completion.

stop([clearQueue,gotoEnd])

Stops all the currently running animations on all the specified elements.

toggle()

Toggle displaying each of the set of matched elements.

 

toggle(speed,[callback])

Toggle displaying each of the set of matched elements using a graceful animation and firing an optional call back after completion.

toggle(switch)

Toggle displaying each of the set of matched elements based upon the switch(true shows all elements , false hides all elements)

jQuery.fx.off

Globally disable all animations.

jQuery – Ajax

Ajax is an acronym standing for Asynchronous JavaScript and XML and this technology help us to load data from the server without a browser page refresh.

jQuery is a great tool which provides a rich set of AJAX methods to develop next generation web application.

Loading Simple Data

This is very easy to load any static or dynamic data using jQuery AJAX, jQuery provides load() method to do the job:

Syntax

Here is the simple syntax for load() method:

[selector].load( URL, [data], [callback] );

Here is the description of all the parameters:

URL: The URL of the server-side resource to which the request is sent. It could be a CGI,APS,JSP or PHP script which generates data dynamically or out of a database.

Data: This optional parameter represents an object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method.Id omitted, the GET method is used.

Call-back: A call-back function invoked after the response datas has been loaded in to the elements of the matched set. The first parameter passed to this function is the response text received from the server and second parameter is the status code.

Example

Consider the following HTML file with a small jQuery coding:

<html>

<head>

<title>the title </title>

<script type=”text/javascript”

Src=”/jQuery/jQuery-1.3.2.min.js”></script>

<script type=”text/javascript” language =”javascript”>

${document}.ready{function}{}{

${“#driver”}.click{function{event}{

${“#stage’}.load{‘/jQuery/result.html’};

}};

</script>

</head>

<body>

<p> Click on the button to load result.html file:</p>

<div id=”stage” style=”background-color:blue;”>

STAGE

</div>

<input type=”button” id=”driver” value=”Load Data”/>

<body>

</html>

Here load( ) initiates an Ajax request to the specified URL/jQuery/result.html file. After loading this file all the content would be populated inside<div>tagged with ID stage. Assuming, our /jQuery/result.html file has just one HTML line:

<h1>THIS IS RESULT….</h1>

When you click the given button,then result.html file get loaded.


jQuery AJAX Methods

You have seen basic concept of AJAX using jQuery. Following table lists down all important jQuery AJAX methods which you can based your programming need:

Methods and Description

jQuery.ajax{options}

load a remote page using an HTTP request.

jQuery.ajaxSetup{options}

Set up global settings for AJAX requests.

jQuery.ger{url,[data],[callback],[type]}

Load a remote page using an HTTP GET request.

jQuert.getJson{url,[data],[callback]}

Load JSON data using an HTTP GET request.

jQuery.getScript{url,{callback}]

Loads and executes aJava Script file using anHTTP GET request.

jQuery.post{url,[data].[callback],[type]}

Load  a  remote page using anHTTP POST request.

Load{url,[data][callback]}

Load a HTML from a remote file and inject it inot the DOM.

Serialize{}

Serializes a set of input elements into a string of data.

SerializeArray{}

Serializes all forms and form elements like the .serialize{} method but returns a JSON data structure for you to work with.

jQuery AJAX Events

You can call various jQuery methods during the life cycle of AJAX call progress. Based on different events/stages following methods are available:

You can go through all the AJAX Events

Methods and Description

ajaxComplete{callback}

Attach a function to be executed whenever an AJAX request completes.

ajaxStart{call back}

Attach a function to be executed whenever an AJAX request begins and there is none alreadyactive.

Ajax Error{callback}

Attach afunction to be executed whenever an AJAX request fails.

ajaxSend{callback}

Attach a function to be executed before an AJAX request is sent.

ajaxStop{callback}

Attach a function to be executed whenver all AJAX requests have ended.

ajaxSucess{call-back}

Attach a function to be executed whenever an AJAX request completes successfully.

Working with jQuery Ajax Features

jQuery allows Ajax requests to be made from a page:

Allows parts of a page to be updated

Cross-Browser support

Simple API

GET and POST supported

Load JSON,XML,HTML or even scripts

varxmlHttp=null;

if{window.XMLHttpReques{{

//If IE7,Mozilla,Safari,and so on:Use native object.

xmlHttp=new XMLHttpRequest{};

}

Else

{

If{window.ActiveXObject}{

//_ _ _ otherwise,use the ActiveX control for IES.x and IE6.

xmlHttp=new ActiveXObject{‘MSXML2.XMLHTTP.3.0’};

 jQuery Ajax Functions

jQuery provides several functions that can be used to send and receive data:

$(selector).load():Loads HTML data from the server

$.get() and $.post():Get raw data from the server

$getJSON():Get/Post and return JSON

$.ajax():Provides core functionality

jQuery Ajax functions work with REST APIs,Web Services and more

Using load()

$(selector).load(url,data,callback) allows HTML content to be loaded from a server and added into a DOM object:

$(document).ready(function(){

$(‘#HelpButton’).click(function(){

$(‘#MyDiv’).load(‘HelpDetails.html’);

});

});

Using load() With a Selector

A selector can be added after the URL to filter the content that is returned from calling load():

$(‘#MyDiv’).load(‘HelpDetails.html#MainTOC’);

Passing Data using load()

Data can be passed to the server using load(url,data):

$(‘#MyDiv’).load(‘GetCustomers.apsx’,

{PageSize:25});

Using a Call-back Function with load()

Load() can be passed a call-back function:

$(‘#OutputDiv’).load(‘Not Found.html’,

Function(response,status,xhr}{

If(status==”error”){

Alert(xhr.statusText);

}

});

<script.type”text/javascript”>

$(document).ready(function(){

$(‘#HelpButton’).click(function(){

$(‘#OutputDiv’).load(‘NotFound.html[,

Function(response,status,xhr){

If(statuys==”error”){

Alert(Error:’+xhr.status.Text);

}

});

});

</script>

Using get()

$.get(url,data,callback,datatype)can retrieve data from a server:

$.get(‘HelpDetails.html’,function9data){

${#OutputDiv’).html(data);

});

<script type=”text/javascript”>

$(document).ready(function(){

$(#MyButton’).click{function(){

$.get(;../HelpDetails.html’,function(data){

$(#OutputDiv’).html(data);

});

$.get(‘../Customer}son,aspx”,(id:5},function(data){

Alert(‘ID:’+data.ID+’ ‘+

Data.FirstName+’ ‘+data.LastName);

},’json’);

});

});

</script>

script type=”text/javascript”>

$(document).ready(function(){

$(#MyButton’).click{function(){

$.getJSON(‘../CustomerJson.aspx’,{id:5},

function(data){

alert(‘ID:’+data.ID+’   ‘+

data.FirstName+’   ‘+data.LastName);

});

});

});

</script>

Using Post()

$.post(url,data,callback,datatype)can post data to a server and retrieve results

$.post(‘GetCustomers.aspx’,{PageSize:15},

Function(data){

$(‘#OutputDiv’).html(data);

}

);

Using post() to Call a WCF Service

Post() can also be used to interact with an Ajax-enabled WCF service:

$.post(‘CustomerService.svc/GetCustomers’,

Null,function(data){

Var cust=data.d[o};

Alert (cust.FirstName+’   ‘+

Cust.LastName);

},  ‘json’);

script type=”text/javascript”>

$(document).ready(function(){

$(#MyButton’).click{function(){

$.post(‘../GetCustomers.aspx’,{PageSize:15},

Function(data){

$(‘#OutputDiv’).html(data);

});

});

});

</script>

<script type=”text/javascript”>

$(document).ready(function(){

$(#MyButton’).click{function(){

$.post(‘../CustomerService.svc/GetCustomers’,null,

Var cust=data.d[o];

${‘#OutputDiv’).html(cust.FirstName+’ ‘+cust.LastName

},’json’);

});

});

});

</script>

Ajax()Functions

The Ajax() function provides extra control over making Ajax calls to a server

Configure using JSON properties:

Content type

Data

Data type

Error

Success

Type(GET or POST)

Using the Ajax() Function

The Ajax() function is configured by assigning values to JSON properties:

$.ajax({

url:’../CustomerSerivce.svc/InserCustomer’,

data:customer,

dataType:’json’,

success:function (data,status,xhr){

alert(“Insert status:”+data.d.status+’/n’+data.d.Message};

},

Error:function(xhr,status,error){

Alert(‘Error occurred:’+status);

}

<script type=’text/javascript”>

$(document).ready{function{}{

${‘#MyButton’}.click{function{}{

Var customer=’cust=’+

]SON.stringify{{

FirstName:${‘#FirstNameTB’}.val{},

LastName:${‘#lastNameTB’}.val{},

});

$.ajax{{

url:’../CustomerService.svc/InsertCustomer’,

data:customer,

datatype:json’,

success:function{data,status,xhr}{

${‘#OutputDiv’}.html{Insert status:’+data.d.Status

},

Error:function{xhr,status,error}{

Alert{‘Error occurred:’ +status};

}

}};

jQueryAjaxGet

Src

Com.nareshit.jquert.servlet

WeatherServlet.java

JRE SystemLibrary

Java EE 5 Libraires

Reference Libraries

  • Commons-beanutils-1.8.1jar
  • Commons-collections-3.2.1jar
  • Commons-lang-2.5.jar
  • Commons-lagging-1.1.1.jar
  • Ezmorph-1.06.jar
  • Json-lib-2.2.3-jdkl15,jar

Lib

WebRoot

META-INF

Script

WEB-INF

Lib

Web.xml

Index.html


Java with jQuery

WeatherServlet.java

Package nareshit.jquery.servelet;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import net. sf.json.JSONObject;

public class WeatherServlet extends HttpServlet{

protected void doPost{HttpServletRequest request,HttpServletResponse

response}throws ServletException,IOException{

String city=request.getParameter{“cityname”};

String report=getWeather{city};

setContentType{‘application/json”};

PrintWriter out=response.getWriter{};

JSONObject json=new JSCNObject{};

//adding properties to json object

put{“city”,city};

put{‘report”,report};

println{json};

flush{};

close{};

}

private String getWeather{String city}{

String report;”

if {city.toLowerCase().equals{“Hyderabad”}}

report= Currently it is not raining in hyderabad.Average

temperature is 20”;

else if{city.toLowerCase9).equals{“Chennai”}}

report=”It’s a rainy season in Chennai now.Better get a umbrella

before going out.”;

else if{city.toLowerCase{}.equals{“Bangalore”}}

report=”It’s mostly cloudy in Banglore.Good weather for a cricket

”;

else

report=”The City you have entered is not present in our sytem.May

be it has been destroyed in last World War or not yet built

by the mankind”;

return report;

}

}

Web.xml

<?xml version=”1.0”encoding=”UTF-8”?>

<web-app id=WebApp_ID”version=”2.4”

xmlns=http://java.sun.com/xml/ns/j2ee

xmlns:xsi=http://www.w3schools.com/xml/schema_schema.asp

xsi:schemaLoaction=”http://java.sun.com/xml/ns/j2ee

http://java.sin.com/xml/ns/j2ee/web-app_2_4.xsd”>

<display-name>test</dispalu-name>

<servlet>

<servlet-name>WeatherServlet</servet-name>

<servlet-class>com.nareshit.jquery.servlet.WeatherServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>WeatherServlet</servet-name>

<url-pattern>/WeatherServlet</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index,html</welcome-file>

</welcome-file-list>

</web-app>

index.html

<!DOCTYPE html PUBLIC “~//w3c//DTD HTML 4.01 Transitional //EN ”  “http://www.w3.org/TR/html14/loose.dtd”>

<html>

<head>

<script type=”text/javascript” src=”script/jquery.js”></script>

<script type=”text/javascript”>

$(document).ready(function() {

$(“#getWeatherReport”).click(function() {

var cityName=$(“#cityName”).val();

$.ajax(

{

url:” . /WeatherServlet ”,

data:{“cityName”: cityName},

dataType:’json’,

success:function(data,status,xhr){

alert(data.report);

},

error: function (xhr,status,error) {

alert(error);

},

type:’POST’

}};

}};

}};

</script>

</head>

<body bgcolor=”yellow”>

<center>

<h1> Ajax with web application </h1>

<hr/><hr/>

<form name=”form1” method=”post”>

Enter Ciyt : <input type=”text” name=”cityName” id=”cityName” />

<input type=”button” name=”getWeatherReport” id=”getWeatherReport” value=”Get Weather” />

</form>

<br/>

<div id=”weatherReport” class=”outputTextArea” style=”width:400px;height:100px;boarder:2px solid green”>

</div>

</center>

</body>

</html>

 

Reference Websites 

jQuery.com

Jqueryui.com

http://codylindley.com/jqueryselectors/

http://appendto.com/community/jquery-vsdoc

http://james.padolsey.com/jquery/#v=1.6.2&fn=jquery.fn.hide

Summary
Review Date
Reviewed Item
jQuery Tutorials
Author Rating
5

Contact US

Need an Instructor Led Training, Contact Us





Enter this code: captcha