You are on page 1of 39

jQuery Reference

jQuery Introduction :
What is jQuery? jQuery is a cross browser, java Script library created by 'John Resig' in 2006 with a nice motto: "Write less, do more". It handles the client side scripting of HTML. jQuery simplifies navigation of a document , select DOM elements, create animations, handle events, and develop Ajax applications. Using jQuery we can also develop plug-in on the top of the JavaScript library. jQuery is java script and can be used with JSP, Servlet, ASP, PHP, CGI and almost all the web programming languages. The jQuery library contains the following features:

HTML element selections HTML element manipulation CSS manipulation HTML event functions JavaScript Effects and animations HTML DOM traversal and modification AJAX Utilities

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> 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 type="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 be performed on the element(s)

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" jQuery uses a combination of XPath and CSS selector syntax. You will learn more about the selector syntax in the next chapter of this tutorial.

The Document Ready Function You might have noticed that all jQuery methods, in our examples, are inside a document.ready() function: $(document).ready(function(){ // jQuery functions go here... }); This is to prevent any jQuery code from running before the document is finished loading (is ready).

jQuery Selectors :
jQuery selectors allow you to select and manipulate HTML elements as a group or as a single element. In the previous chapter we looked at some examples of how to select different HTML elements. It is a key point to learn how jQuery selects exactly the elements you want to apply an effect to. jQuery selectors allow you to select HTML elements (or groups of elements) by element name, attribute name or by content. In HTML DOM terms: Selectors allow you to manipulate DOM elements as a group or as a single node.

jQuery Element Selectors jQuery uses CSS selectors to select HTML elements. $("p") selects all <p> elements. $("p.intro") selects all <p> elements with class="intro". $("p#demo") selects the first <p> element with id="demo". jQuery Attribute Selectors jQuery uses XPath expressions to select elements with given attributes. $("[href]") select all elements with an href attribute. $("[href='#']") select all elements with an href value equal to "#". $("[href!='#']") select all elements with an href attribute NOT equal to "#". $("[href$='.jpg']") select all elements with an href attribute that ends with ".jpg".

jQuery CSS Selectors jQuery CSS selectors can be used to change CSS properties for HTML elements. The following example changes the background-color of all p elements to yellow: $("p").css("background-color","yellow"); Some More Examples Syntax $(this) $("p") $("p.intro") $(".intro") $("#intro") $("ul li:first") $("[href$='.jpg']") $("div#intro .head") Description Current HTML element All <p> elements All <p> elements with class="intro" All elements with class="intro" The first element with id="intro" The first <li> element of each <ul> All elements with an href attribute that ends with ".jpg" All elements with class="head" inside a <div> element with id="intro"

jQuery Selectors : Selector * #id .class element .class.class :first :last :even :odd :eq(index) :gt(no) :lt(no) :not(selector) :header :animated :contains(text) :empty :hidden :visible s1,s2,s3 [attribute] [attribute=value] Example $("*") $("#lastname") $(".intro") $("p") $(".intro.demo") $("p:first") $("p:last") $("tr:even") $("tr:odd") $("ul li:eq(3)") $("ul li:gt(3)") $("ul li:lt(3)") $("input:not(:empty)") $(":header") $(":animated") Selects All elements The element with id=lastname All elements with class="intro" All p elements All elements with the classes "intro" and "demo" The first p element The last p element All even tr elements All odd tr elements The fourth element in a list (index starts at 0) List elements with an index greater than 3 List elements with an index less than 3 All input elements that are not empty All header elements h1, h2 ... All animated elements

$(":contains('W3Schools')") All elements which contains the text $(":empty") $("p:hidden") $("table:visible") $("th,td,.intro") $("[href]") $("[href='default.htm']") All elements with no child (elements) nodes All hidden p elements All visible tables All elements with matching selectors All elements with a href attribute All elements with a href attribute value equal to "default.htm" All elements with a href attribute value not equal to "default.htm" All elements with a href attribute value ending with ".jpg" All input elements All input elements with type="text" All input elements with type="password" All input elements with type="radio" All input elements with type="checkbox" All input elements with type="submit" All input elements with type="reset" All input elements with type="button" All input elements with type="image" All input elements with type="file" All enabled input elements All disabled input elements

[attribute!=value] $("[href!='default.htm']") [attribute$=value] $("[href$='.jpg']") :input :text :password :radio :checkbox :submit :reset :button :image :file :enabled :disabled $(":input") $(":text") $(":password") $(":radio") $(":checkbox") $(":submit") $(":reset") $(":button") $(":image") $(":file") $(":enabled") $(":disabled")

:selected :checked

$(":selected") $(":checked")

All selected input elements All checked input elements

jQuery Events :
The jQuery event handling methods are core functions in jQuery. Event handlers are method that are called when "something happens" in HTML. The term "triggered (or "fired") by an event" is often used. It is common to put jQuery code into event handler methods in the <head> section: 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 a heading</h2> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button>Click me</button> </body> </html>

In the example above, a function is called when the click event for the button is triggered: $("button").click(function() {..some code... } ) The method hides all <p> elements: $("p").hide(); Functions In a Separate File: If your website contains a lot of pages, and you want your jQuery functions to be easy to maintain, put your jQuery functions in a separate .js file. When we demonstrate jQuery here, the functions are added directly into the <head> section, However, sometimes it is preferable to place them in a separate file, like this (refer to the file with the src attribute): Example <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="my_jquery_functions.js"></script> </head>

jQuery Name Conflicts: jQuery uses the $ sign as a shortcut for jQuery.

Some other JavaScript libraries also use the dollar sign for their functions. The jQuery noConflict() method specifies a custom name (like jq), instead of using the dollar sign. jQuery Events: Here are some examples of event methods in jQuery:

Event Method $(document).ready(function) $(selector).click(function) $(selector).dblclick(function) $(selector).focus(function)

Description Binds a function to the ready event of a document (when the document is finished loading) Triggers, or binds a function to the click event of selected elements Triggers, or binds a function to the double click event of selected elements Triggers, or binds a function to the focus event of selected elements

$(selector).mouseover(function) Triggers, or binds a function to the mouseover event of selected elements jQuery Event Methods: Event methods trigger, or bind a function to an event for all matching elements. Trigger example: $("button").click() - triggers the click event for a button element. Binding example: $("button").click(function(){$("img").hide()}) - binds a function to the click event. The following table lists all the methods used to handle events. Method bind() Description Add one or more event handlers to matching elements Eg: Event:Required. Specifies one or more events $("button").bind("click",fun to attach to the elements.Multiple event values ction(){ are separated by space. Must be a valid event. $("p").slideToggle(); }); Data:Optional. Specifies additional data to pass along to the function. Function: Required. Specifies the function to run when the event(s) occur blur() Triggers, or binds a function $(selector).blur() to the blur event of selected Bind a Function to the blur Event elements $(selector).blur(function) Eg: $("input").blur(function(){ $("input").css("backgroundcolor","#D6D6FF"); Syntax $(selector).bind(event,data,function) OR $(selector).bind({event:function, event:function, ...})

}); change() Triggers, or binds a function $(selector).change() to the change event of Bind a Function to the change Event selected elements $(selector).change(function) Eg: $(".field").change(function( ){ $(this).css("backgroundcolor","#FFFFCC"); }); Triggers, or binds a function $(selector).click() to the click event of Bind a Function to the click Event selected elements $(selector).click(function) Eg: $("button").click(function() { $("p").slideToggle(); }); Triggers, or binds a function $(selector).dblclick() to the dblclick event of Bind a Function to the doubleclick Event selected elements $(selector).dblclick(function) Eg: $("button").dblclick(functio n(){ $("p").slideToggle(); }); Add one or more event handlers to current, or future, specified child elements of the matching elements Eg: $("div").delegate("button"," click",function(){ $("p").slideToggle(); }); $(selector).delegate(childSelector,event,data,fu nction) childSelector: Required. Specifies one or more child elements to attach the event handler to. Event: Required. Specifies one or more events to attach to the elements. Multiple event values are separated by space. Must be a valid event. Data: Optional. Specifies additional data to pass along to the function Function: Required. Specifies the function to run when the event(s) occur die() Remove all event handlers added with the live() function Eg: $("p").die(); $(selector).die(event,function) Event: Required. Specifies one or more event handlers to remove. Multiple event values are separated by space. Must be a valid event Function: Optional. Specifies a specific function to remove error() Triggers, or binds a function $(selector).error() to the error event of Bind a Function to the error Event selected elements $(selector).error(function) Eg: $("img").error(function(){ $("img").replaceWith("<p> Error loading image!</p>"); }); The current DOM element within the event bubbling phase Contains the optional data passed to jQuery.fn.bind

click()

dblclick()

delegate()

event.currentTarget

event.data

when the current executing handler was bound event.isDefaultPrevented() Returns whether event.preventDefault() was called for the event object Eg: $("a").click(function(event) { event.preventDefault(); alert("Default prevented: " + event.isDefaultPrevented()) ; }); event.isDefaultPrevented() Event: Required. Specifies the event to check. The event parameter comes from the event binding function

event.isImmediatePropagati Returns whether onStopped() event.stopImmediatePropag ation() was called for the event object event.isPropagationStopped Returns whether () event.stopPropagation() was called for the event object event.pageX The mouse position relative to the left edge of the document Eg: $(document).mousemove(f unction(e){ $("span").text("X: " + e.pageX + ", Y: " + e.pageY); }); event.pageX Event: Required. Specifies the event to use. The event parameter comes from the event binding function

event.pageY

The mouse position relative event.pageY to the top edge of the document Prevents the default action event.preventDefault() of the event Eg: $("a").click(function(event) { event.preventDefault(); }); The other DOM element involved in the event, if any This attribute contains the event.result last value returned by an event handler that was triggered by this event, unless the value was undefined Eg: $("button").click(function(e ){ $("p").html(e.result); });

event.preventDefault()

event.relatedTarget event.result

event.stopImmediatePropag Prevents other event ation() handlers from being called event.stopPropagation() Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event

event.target

The DOM element that event.target initiated the event Eg: $("p, button, h1, h2").click(function(event){ $("div").html("Triggered by a " + event.target.nodeName + " element."); }); This attribute returns the event.timeStamp number of milliseconds since January 1, 1970, when the event is triggered Eg: $("button").click(function(e vent){ $("span")html(event.timeSt amp); });

event.timeStamp

event.type

Describes the nature of the event.type event Eg: $("p").bind('click dblclick mouseover mouseout',function(event){ $("div").html("Event: " + event.type); }); Which key or button was event.which pressed for a key or button event Eg: $("input").keydown(functio n(event){ $("div").html("Key: " + event.which); }); Triggers, or binds a function $(selector).focus() to the focus event of Bind a Function to the focus Event selected elements $(selector).focus(function) Eg: $("input").focus(function(){ $("input").css("backgroundcolor","#FFFFCC"); });

event.which

focus()

focusin()

Binds a function to the $(selector).focusin(function()) focusin event of selected elements Eg: $("div").focusin(function(){ $(this).css("backgroundcolor","#FFFFCC"); });; Binds a function to the $(selector).focusout(function()) focusout event of selected elements Eg: $("div").focusout(function() { $("this").css("backgroundcolor","#FFFFFF");

focusout()

}); hover() Binds one or two functions to the hover event of selected elements Eg: $("p").hover(function(){ $("p").css("backgroundcolor","yellow"); },function(){ $("p").css("backgroundcolor","#E9E9E4"); }); $(selector).hover(inFunction,outFunction) inFunction: Required. Specifies the function to run when the mouseenter event occurs. If this is the only parameter specified, this function will be run for both the mouseenter and mouseleave events. outFunction:Optional. Specifies the function to run when the mouseleave event occurs

keydown()

Triggers, or binds a function $(selector).keydown() to the keydown event of Bind a Function to the keydown Event selected elements $(selector).keydown(function) Eg: $("input").keydown(functio n(){ $("input").css("backgroundcolor","#FFFFCC"); });

keypress()

Triggers, or binds a function $(selector). keypress () to the keypress event of Bind a Function to the keypress Event selected elements $(selector).keypress( function) Eg: $("input").keydown(functio n(){ $("span").text(i+=1);}); Triggers, or binds a function $(selector). keyup () to the keyup event of Bind a Function to the keyup Event selected elements $(selector).keyup( function) Eg: $("input").keyup(function() { $("input").css("backgroundcolor","#D6D6FF"); });

keyup()

live()

Add one or more event handlers to current, or future, matching elements Eg: $("button").live("click",func tion(){ $("p").slideToggle(); });

$(selector).live(event,data,function) Event: Required. Specifies one or more events to attach to the elements. Multiple event values are separated by space. Must be a valid event. Data: Optional. Specifies additional data to pass along to the function Function: Required. Specifies the function to run when the event(s) occur

load()

Triggers, or binds a function $(selector).load(function) to the load event of selected elements Eg: $("img").load(function(){ $("div").text("Image loaded"); }); Triggers, or binds a function $(selector). mousedown () to the mouse down event of Bind a Function to the mousedown Event selected elements $(selector).mousedown( function) Eg: $("button").mousedown(fun ction(){

mousedown()

$("p").slideToggle(); }); mouseenter() Triggers, or binds a function $(selector). mouseenter () to the mouse enter event of Bind a Function to the mouseenter Event selected elements $(selector).mouseenter( function) Eg: $("p").mouseenter(function (){ $("p").css("backgroundcolor","yellow"); }); Triggers, or binds a function $(selector). mouseleave () to the mouse leave event of Bind a Function to the mouseleave Event selected elements $(selector).mouseleave( function) Eg: $("p").mouseleave(function (){ $("p").css("backgroundcolor","#E9E9E4"); }); Triggers, or binds a function $(selector). mousemove () to the mouse move event of Bind a Function to the mousemove Event selected elements $(selector).mousemove( function) Eg: $(document).mousemove(f unction(e){ $("span").text(e.pageX + ", " + e.pageY); }); Triggers, or binds a function $(selector). mouseout () to the mouse out event of Bind a Function to the mouseout Event selected elements $(selector).mouseout( function) Eg: $("p").mouseout(function() { $("p").css("backgroundcolor","#E9E9E4"); }); Triggers, or binds a function to the mouse over event of selected elements $(selector). mouseover () $("p").mouseover(function( Bind a Function to the mouseover Event ){ $(selector).mouseover( function) $("p").css("backgroundcolor","yellow"); }); Triggers, or binds a function $(selector). mouseup () to the mouse up event of Bind a Function to the mouseup Event selected elements $(selector).mouseup( function) Eg: $("button").mouseup(functi on(){ $("p").slideToggle(); }); Add one or more event handlers to matching elements. This handler can only be triggered once per element Eg: $("p").one("click",function() { $(selector).one(event,data,function) Event: Required. Specifies one or more events to attach to the elements. Multiple event values are separated by space. Must be a valid event. Data: Optional. Specifies additional data to pass along to the function Function: Required. Specifies the function to

mouseleave()

mousemove()

mouseout()

mouseover()

mouseup()

one()

$(this).animate({fontSize:" run when the event(s) occur +=6px"}); }); ready() Binds a function to the ready event of a document (when an HTML document is ready to use) Eg: $(document).ready(function (){ $("button").click(function() { $("p").slideToggle(); }); }); resize() Triggers, or binds a function $(selector). resize () to the resize event of Bind a Function to the resize Event selected elements $(selector).resize( function) Eg: $(window).resize(function() { $('span').text(x+=1); }); Triggers, or binds a function $(selector). scroll () to the scroll event of Bind a Function to the scroll Event selected elements $(selector).scroll( function) Eg: $("div").scroll(function() { $("span").text(x+=1); }); Triggers, or binds a function $(selector). select () to the select event of Bind a Function to the select Event selected elements $(selector).select( function) Eg: $("input").select(function() { $("input").after(" Text marked!"); }); Triggers, or binds a function $(selector). submit () to the submit event of Bind a Function to the submit Event selected elements $(selector).submit( function) Eg: $("form").submit(function(e ){ alert("Submitted"); }); Binds two or more functions to the toggle between for the click event for selected elements Eg: $("p").toggle(function(){ $("body").css("backgroundcolor","green");}, function(){ $("body").css("backgroundcolor","red");}, function(){ $(selector).toggle(function(),function(),function( ),...) Function: Required. Specifies a function to run every EVEN time the element is clicked Function: Required. Specifies a function to run every odd time the element is clicked Function: Optional. Specifies additional functions to toggle between $(document).ready(function) OR $().ready(function) OR $(function)

scroll()

select()

submit()

toggle()

$("body").css("backgroundcolor","yellow");} ); trigger() Triggers all events bound to the selected elements Eg: $("button").click(function() { $(selector).trigger(event,[param1,param2,...]) Event : Required. Specifies the event to trigger for the specified element. Can be a custom event (attached using the bind() function), or any of the standard events param1,param2,...:Optional. Additional $("input").trigger("select"); parameters to pass on to the event handler. }); Additional parameters are especially useful with custom events Triggers all functions bound to a specified event for the selected elements Eg: $("button").click(function() { $("input").triggerHandler("s elect"); }); unbind() Remove an added event handler from selected elements Eg: $("button").click(function() { $("p").unbind(); }); $(selector).unbind(event,function) Event: Optional. Specifies one or more events remove from the elements. Multiple event values are separated by space. If this is the only parameter specified, all functions bound to the specified event will be removed. Function : Optional. Specifies the name of the function to unbind from the specified event for the element $(selector).undelegate(selector,event,function) Selector: Optional. Specifies the selector to remove event handlers from Event: Optional. Specifies one or more event types to remove handler functions from Function: Optional. Specifies a specific event handler function to remove $(selector).triggerHandler(event,[param1,para m2,...]) Event: Required. Specifies the event to trigger for the specified element. Param1,param2, : Optional. Additional parameters to pass on to the event handler.

triggerHandler()

undelegate()

Remove an event handler to selected elements, now or in the future Eg: $("body").undelegate();

unload()

Triggers, or binds a function $(selector).unload(function) to the unload event of selected elements Eg: $(window).unload(function( ){ alert("Goodbye!"); });

jQuery Effects :
The following table lists all the methods used to create animation effects. Method animate() Description Syntax

Performs a custom animation (of a set of CSS The syntax and description for animate is properties) for selected elements given below after this table.

clearQueue() Removes all queued functions for the selected $(selector).stop(queueName) element Eg: queueName: Optional. Specifies the name of $("#stop").click(function(){ the queue to stop. Default is "fx", the $("#box").clearQueue(); standard effects cure. }); delay() dequeue() fadeIn() Sets a delay for all queued functions for the selected element Runs the next queued functions for the selected element Gradually changes the opacity, for selected elements, from hidden to visible. Eg: $(".btn2").click(function(){ $("p").fadeIn(); }); $(selector).fadeIn(speed,callback) Speed: Optional. Specifies the speed of the fading effect. Default is "normal". Possible values: milliseconds(like 1500) , slow, normal, fast. Callback: Optional . A function to be executed after the fadeIn() method is completed. fadeOut() Gradually changes the opacity, for selected elements, from visible to hidden. Eg: $(".btn1").click(function(){ $("p").fadeOut(); }); $(selector).fadeIn(speed,callback) Speed: Optional. Specifies the speed of the fading effect. Default is "normal". Possible values: milliseconds(like 1500) , slow, normal, fast. Callback: Optional . A function to be executed after the fadeIn() method is completed. fadeTo() Gradually changes the opacity, for selected elements, to a specified opacity. Eg: $("button").click(function(){ $("p").fadeTo(1000,0.4); }); $(selector).fadeTo(speed,opacity,callback) Speed: Optional. Specifies the speed of the fading effect. Default is "normal". Possible values: milliseconds(like 1500) , slow, normal, fast. Callback: Optional . A function to be executed after the fadeIn() method is completed. Opacity: Required. Specifies the opacity to fade to. Must be a number between 0.00 and 1.00 hide() Hides selected elements Eg: $(".btn1").click(function(){ $("p").hide(); }); $(selector).hide(speed,callback) Speed: Optional. Specifies the speed of the fading effect. Default is "normal". Possible values: milliseconds(like 1500) , slow, normal, fast. Callback: Optional . A function to be executed after the fadeIn() method is completed. queue() Shows the queued functions for the selected element Shows hidden selected elements $(selector).show(speed,callback)

show()

Eg: $(".btn2").click(function(){ $("p").show(); });

Speed: Optional. Specifies the speed of the fading effect. Default is "normal". Possible values: milliseconds(like 1500) , slow, normal, fast. Callback: Optional . A function to be executed after the fadeIn() method is completed.

slideDown() Gradually changes the height, for selected elements, from hidden to visible Eg: $(".btn2").click(function(){ $("p").slideDown(); });

$(selector).slideDown(speed,callback) Speed: Optional. Specifies the speed of the fading effect. Default is "normal". Possible values: milliseconds(like 1500) , slow, normal, fast. Callback: Optional . A function to be executed after the fadeIn() method is completed.

slideToggle() Toggles between slideUp() and slideDown() for selected elements Eg: $("button").click(function(){ $("p").slideToggle(); });

$(selector).slideToggle(speed,callback) Speed: Optional. Specifies the speed of the fading effect. Default is "normal". Possible values: milliseconds(like 1500) , slow, normal, fast. Callback: Optional . A function to be executed after the fadeIn() method is completed.

slideUp()

Gradually changes the height, for selected elements, from visible to hidden Eg: $("button").click(function(){ $("p").slideUp(); });

$(selector).slideUp(speed,callback) Speed: Optional. Specifies the speed of the fading effect. Default is "normal". Possible values: milliseconds(like 1500) , slow, normal, fast. Callback: Optional . A function to be executed after the fadeIn() method is completed.

stop()

Stops a running animation on selected elements Eg: $("#stop").click(function(){ $("div").stop(); });

$(selector).stop(stopAll,goToEnd) StopAll : Optional. A Boolean value specifying whether or not to stop the queued animations as well. Default is false goToEnd : Optional. A Boolean value specifying whether or not to complete the current animation immediately. Default is false

toggle()

Toggles between hide() and show(), or custom functions, for selected elements Eg: $("button").click(function(){ $("p").toggle(); });

$(selector).toggle(speed,callback) Speed: Optional. Specifies the speed of the fading effect. Default is "normal". Possible values: milliseconds(like 1500) , slow, normal, fast. Callback: Optional . A function to be executed after the fadeIn() method is completed.

jQuery Effect animate() Method :

Example

"Animate" a div element, by changing its height: $("#btn1").click(function(){ $("#box").animate({height:"300px"}); });

Definition and Usage The animate() method performs a custom animation of a set of CSS properties. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect. Only numeric values can be animated (like "margin:30px"). String values cannot be animated (like "background-color:red"). Note: Use "+=" or "-=" for relative animations. Syntax

(selector).animate({styles},speed,easing,callback) Parameter styles Description Required. Specifies one or more CSS properties to animate, and the values to animate to. Note: The styles are set with DOM names (like "fontSize"), not CSS names (like "font-size"). The possible CSS style values are:

backgroundPosition borderWidth borderBottomWidth borderLeftWidth borderRightWidth borderTopWidth borderSpacing margin marginBottom marginLeft marginRight marginTop outlineWidth padding paddingBottom paddingLeft paddingRight paddingTop height width


speed

maxHeight maxWidth minHeight minWidth font fontSize bottom left right top letterSpacing wordSpacing lineHeight textIndent

Optional. Specifies the speed of the animation. Default is "normal" Possible values:


easing

milliseconds (like 1500) "slow" "normal" "fast"

Optional. Specifies an easing function that sets the speed in different points of the animation. Built-in easing functions are:

swing linear

More easing functions are available in external plugins. callback Optional. A function to be executed after the animation completes.

Alternate Syntax (selector).animate({styles},{options}) Parameter styles options Description Required. Specifies one or more CSS properties to animate, and the values to animate to (See possible values above) Optional. Specifies additional options for the animation. Possible values:

speed - set the speed of the animation easing - specify the easing function to use callback - specifies a function to be executed after the animation completes step - specifies a function to be executed after each step in the animation queue - a Boolean value specifying whether or not to place the animation in the effects cue

specialEasing - a map of one or more CSS properties from the stylesparameter, and their corresponding easing functions

jQuery Callback Functions:

A callback function is executed after the current animation is 100% finished. jQuery Callback Functions A callback function is executed after the current animation (effect) is finished.JavaScript statements are executed line by line. However, with animations, the next line of code can be run even though the animation is not finished. This can create errors.To prevent this, you can create a callback function. The callback function will not be called until after the animation is finished. jQuery Callback Example Typical syntax: $(selector).hide(speed,callback) The callback parameter is a function to be executed after the hide effect is completed: Example with Callback $("p").hide(1000,function(){ alert("The paragraph is now hidden"); });

Without a callback parameter, the alert box is displayed before the hide effect is completed: Example without Callback $("p").hide(1000); alert("The paragraph is now hidden");

jQuery HTML Manipulation :


jQuery contains powerful methods (functions) for changing and manipulating HTML elements and attributes. Changing HTML Content $(selector).html(content) The html() method changes the contents and (innerHtml) of matching HTML elements. Eg: $("p").html("W3Schools"); The following table lists all the methods used to manipulate the DOM. The methods below work for both HTML and XML documents. Exception: the html() method. Method addClass() Description Adds one or more classes (for CSS) to selected elements Eg: $("button").click(function(){ $("p:first").addClass("intro"); }); Syntax $(selector).addClass(class) class : Required. Specifies one or more class names to be added //Add class using a function. $(selector).addClass(function(index,oldclass)) function(index,oldclass) :Required. Specifies a function that returns one or more class names to be added. index - Optional. Receives the index position of the selector oldclass - Optional. Receives the old class value of the selector after() Inserts content after selected elements Eg: $("button").click(function(){ $("p").after("<p>Hello world!</p>"); }); $(selector).after(content) content : Required. Specifies the content to insert (can contain HTML tags) //Insert content using a function $(selector).after(function(index)) function(index) : Required. Specifies a function that returns the content to insert. index - Optional. Receives the index position of the selector append() Inserts content at the end of (but still inside) selected elements Eg: $("button").click(function(){ $("p").append("<p>Hello world!</p>"); }); $(selector).append(content) content : Required. Specifies the content to insert (can contain HTML tags) //Insert content using a function $(selector).append(function(index)) function(index) : Required. Specifies a function that returns the content to insert. index - Optional. Receives the index position of the selector $(content).appendTo(selector) content : Required. Specifies the content to insert (can contain HTML tags) selector : Required. Specifies on which elements to append the content $(selector).attr(attribute)

appendTo()

Inserts content at the end of (but still inside) selected elements Eg: $("button").click(function(){ $("<b>Hello World!</b>").appendTo("p"); }); Sets or returns an attribute and value of selected elements

attr()

Eg: $("button").click(function(){ $("img").attr("width","150"); }); before() Inserts content before selected elements Eg: $("button").click(function(){ $("p").before("<p>Hello world!</p>"); });

attribute : Specifies the attribute to get the value of

$(selector).before(content) content : Required. Specifies the content to insert (can contain HTML tags) //Insert content using a function $(selector).before(function(index)) function(index) : Required. Specifies a function that returns the content to insert. index - Optional. Receives the index position of the selector

clone()

Makes a copy of selected elements Eg: $("button").click(function(){ $("p").clone().appendTo("body"); }); Removes (but keeps a copy of) selected elements Eg: $("button").click(function(){ $("p").detach(); }); Removes all child elements and content from selected elements Eg: $("button").click(function(){ $("p").empty(); }); Checks if any of the selected elements have a specified class (for CSS) Eg: $("button").click(function(){ alert($("p").hasClass("intro")); }); Sets or returns the content of selected elements Eg: $("button").click(function(){ $("p").html("Hello <b>world</b>!"); });

$(selector).clone(includeEvents) includeEvents : Optional. A boolean value that specifies whether or not the event handlers should be copied. By default, event handlers are not included in the copy. $(selector).detach()

detach()

empty()

$(selector).empty()

hasClass()

$(selector).hasClass(class) Class : Required. Specifies the class to search for in the selected elements

html()

$(selector).html() OR $(selector).html(content) Content : Specifies the new content for the selected elements (can contain HTML tags) OR $(selector).html(function(index,oldcontent)) function(index,oldcontent) : Specifies a function that returns the new content for the selected elements. index - Optional. Receives the index position of the selector oldcontent - Optional. Receives the current content of the selector

insertAfter()

Inserts HTML markup or elements after selected elements Eg: $("button").click(function(){ $("<span>Hello world!</span>").insertAfter("p"); });

$(content).insertAfter(selector) content : Required. Specifies the content to insert. Possible values:A selector expression, HTML markup. Selector : Required. Specifies where to insert the content $(content). insertBefore (selector) content : Required. Specifies the content to insert.

insertBefore() Inserts HTML markup or elements before selected elements Eg:

$("button").click(function(){ $("<span>Hello world!</span>"). insertBefore ("p"); }); prepend() Inserts content at the beginning of (but still inside) selected elements Eg: $("button").click(function(){ $("p").prepend(" <b>Hello world!</b>"); });

Possible values : A selector expression, HTML markup. Selector : Required. Specifies where to insert the content

$(selector).prepend(content) Content : Required. Specifies the content to insert (can contain HTML tags) //Prepare content using a function. $(selector).prepend(function(index,html)) function(index,html) : Required. Specifies a function that returns the content to insert. index - Optional. Receives the index position of the selector html - Optional. Receives the current HTML of the selector

prependTo()

Inserts content at the beginning of (but still inside) selected elements Eg: $("button").click(function(){ $("<b>Hello World!</b>").prependTo("p"); }); Removes selected elements Eg: $("button").click(function(){ $("p").remove(); }); Removes an attribute from selected elements Eg: $("button").click(function(){ $("p").removeAttr("style"); });

$(content).prependTo(selector) Content : Required. Specifies the content to insert (can contain HTML tags) Selector : Required. Specifies on which elements to insert the content $(selector).remove()

remove()

removeAttr()

$(selector).removeAttr(attribute) attribute : Required. Specifies the attribute to remove

removeClass() Removes one or more classes (for CSS) from selected elements Eg: $("button").click(function(){ $("p").removeClass("intro"); });

$(selector).removeClass(classname) classname : Optional. Specifies one or more class names to remove. To remove several classes, separate the class names with space. Note: If this parameter is empty, all classes will be removed. //Remove class using a function $(selector).removeClass(function(index,oldclass)) function(index,oldclass) :function that returns one or more class names to remove. ->index - Optional. Receives the index position of the selector ->oldclass - Optional. Receives the old class value of the selector

replaceAll()

Replaces selected elements with new content Eg: $("button").click(function(){ $("p").replaceAll("<b>Hello world!</b>"); });

$(content).replaceAll(selector) content : Required. Specifies the new content. Possible values: HTML code - like "<div>Hello world</div>" New elements - like document.createElement("div") Existing elements - like $(".div1") Selector : Required. Specifies which elements to be

replaced replaceWith() Replaces selected elements with new content Eg: $("button").click(function(){ $(selector).replaceWith(content)

content : Required. Specifies the new content. Possible values: HTML code - like "<div>Hello world</div>" $("p:first").replaceWith("<b>Hello New elements - like document.createElement("div") world!</b>"); Existing elements - like $(".div1") }); //Replace elements using a function $(selector).replaceWith(function()) Function : Required. A function that returns the new content to replace the selected elements with Sets or returns the text content of $(selector).text() selected elements //Set text content Eg: $(selector).text(content) $("button").click(function(){ // Set text content using a function $("p").text("Hello world!"); $(selector).text(function(index,oldcontent)) }); Toggles between adding/removing one or more classes (for CSS) from selected elements Eg: $("button").click(function(){ $("p").toggleClass("main"); }); $(selector).toggleClass(class,switch) Class : Required. Specifies one or more class names to add or remove. To specify several classes, separate the class names with a space. switch : Optional. A Boolean value specifying if the class should be added (true), or removed (false).

text()

toggleClass()

unwrap()

Removes the parent element of the $(selector).unwrap() selected elements Eg: $("button").click(function(){ $("p").unwrap(); }); Sets or returns the value attribute of the selected elements (form elements) Eg: $("button").click(function(){ $("input:text").val("Glenn Quagmire"); }); $(selector).val() //Set text content $(selector).val(value) Value : Specifies the value of the value attribute // Set text content using a function $(selector).text(function(index,oldvalue)) function(index,oldvalue) : Specifies a function that returns the value to set. index - Optional. Receives the index position of the selector oldvalue - Optional. Receives the current value attribute of the selector

val()

wrap()

Wraps specified HTML element(s) $(selector).wrap(wrappingElement) around each selected element wrappingElement : Required. Specifies what HTML Eg: element(s) to wrap around each selected element. $("button").click(function(){ Possible values: $("p").wrap("<div></div>"); -> elements - like "<div></div>" or }); "<div><b></b></div>" -> element - like document.createElement("div") ->isting elements - like $(".div1") Note: Existing elements will be copied and wrapped around each selected element //Wrap Elemnts using a function $(selector).wrap(function()) Function : Required. Specifies a function that returns the wrapping element

wrapAll()

Wraps specified HTML element(s) around all selected elements Eg: $("button").click(function(){

$(selector).wrapAll(wrappingElement) wrappingElement : Required. Specifies what HTML element(s) to wrap around each selected element. Possible values: -> elements - like "<div></div>" or $("p").wrapAll("<div></div>"); "<div><b></b></div>" }); -> element - like document.createElement("div") ->isting elements - like $(".div1") Note: Existing elements will be copied and wrapped around each selected element //Wrap Elemnts using a function $(selector).wrapAll(function()) Function : Required. Specifies a function that returns the wrapping element

wrapInner()

Wraps specified HTML element(s) $(selector).wrapInner(wrappingElement) around the content of each wrappingElement : Required. Specifies what HTML selected element element(s) to wrap around each selected element. Eg: Possible values: $("button").click(function(){ -> elements - like "<div></div>" or $("p").wrapAlldiv></div>"); "<div><b></b></div>" }); -> element - like document.createElement("div") ->isting elements - like $(".div1") Note: Existing elements will be copied and wrapped around each selected element //Wrap Elemnts using a function $(selector).wrapInner(function()) Function : Required. Specifies a function that returns the wrapping element

jQuery CSS Manipulation :


jQuery has one important method for CSS manipulation: css() The css() method has three different syntaxes, to perform different tasks.

css(name) - Return CSS property value css(name,value) - Set CSS property and value css({properties}) - Set multiple CSS properties and values

Return CSS Property Use css(name) to return the specified CSS property value of the FIRST matched element: Example $(this).css("background-color");

Set CSS Property and Value Use css(name,value) to set the specified CSS property for ALL matched elements: Example $("p").css("background-color","yellow");

Set Multiple CSS Property/Value Pairs Use css({properties}) to set one or more CSS property/value pairs for the selected elements: Example $("p").css({"background-color":"yellow","font-size":"200%"});

jQuery CSS Methods The following table lists all the methods used to manipulate CSS properties. Method Description Syntax $(selector).addClass(class) class : Required. Specifies one or more class names to be added //Add class using a function. $(selector).addClass(function(index,oldclass)) function(index,oldclass) :Required. Specifies a function that returns one or more class names to be added. index - Optional. Receives the index position of the selector oldclass - Optional. Receives the old class value of the selector Sets or returns one or more style properties $(selector).css(name) Name : Required. Specifies the name of a CSS property. for selected elements

addClass() Adds one or more classes to selected Repeated(HTML elements Prop) Eg: $("button").click(function(){ $("p:first").addClass("intro"); });

css()

Eg: button").click(function(){ $("p").css("color","red"); });

This parameter can contain any CSS property. Like "color" //Set css property $(selector).css(name,value) Name : Required. Specifies the name of a CSS property. This parameter can contain any CSS property. Like "color" Value : Optional. Specifies the value of the CSS property. This parameter can contain any CSS property value. Like "red". If an empty string value is set, it removes the specified property from the element. //Set css property using a function $(selector).css(name,function(index,oldvalue)) Name : Required. Specifies the name of a CSS property. This parameter can contain any CSS property. Like "color" function(index,oldvalue) : Specifies a function that returns the new value for the CSS property. index - Optional. Receives the index position of the selector oldvalue - Optional. Receives the current value of the CSS property

hasClass() Checks if any of the selected elements have $(selector).hasClass(class) Repeated(HTML a specified class Class : Required. Specifies the class to search for in the Prop) Eg: selected elements $("button").click(function(){ alert($("p").hasClass("intro")); }); height() Sets or returns the height of selected elements Eg: $("button").click(function(){ $("p").height(50); }); $(selector).height() //Set height $(selector).height(value) Value : Required. Specifies the height in px, em, %, etc. Default unit is px //Set height using a function $(selector).height(function(index,oldheight)) function(index,oldheight) : Specifies a function that returns the new height of selected elements. ->dex - Optional. Receives the index position of the selector ->dheight - Optional. Receives the current height of the selector offset() Sets or returns the position (relative to the document) for selected elements Eg: $("button").click(function(){ x=$("p").offset(); alert("Left offset: " + x.left + " Top offset: " + x.top); $(selector).offset() //Set height $(selector).offset(value) Value : Required. Specifies the top and left coordinates in pixels. Possible values:

});

=>Value pair , like {top:100,left:0} => An object with top and left properties //Set height using a function $(selector).width(function(index,oldoffset)) function(index,oldoffset) : Specifies a function that returns the new height of selected elements. ->index - Optional. Receives the index position of the selector -> oldoffset - Optional. Receives the current height of the selector $(selector).offsetParent()

offsetParent()

Returns the first parent element that is positioned Eg: $("button").click(function(){ $("p").offsetParent().css("backgroundcolor","red"); });

position()

Returns the position (relative to the parent $(selector).position() element) of the first selected element Eg: $("button").click(function(){ x=$("p").position(); alert("Left position: " + x.left + " Top position: " + x.top); }); $(selector).removeClass(classname) classname : Optional. Specifies one or more class names to remove. To remove several classes, separate the class names with space. Note: If this parameter is empty, all classes will be removed. //Remove class using a function $(selector).removeClass(function(index,oldclass)) function(index,oldclass) :function that returns one or more class names to remove. ->index - Optional. Receives the index position of the selector ->oldclass - Optional. Receives the old class value of the selector Sets or returns the horizontal position of the //Return horizontal scrollbar position $(selector).scrollLeft() scrollbar for the selected elements //Set horizontal scrollbar position Eg: $(selector).scrollLeft(position) $("button").click(function(){ alert($("div").scrollLeft()+" px"); Position : Optional. Specifies the new position in pixels }); Sets or returns the vertical position of the scrollbar for the selected elements Eg: $("button").click(function(){ alert($("div").scrollTop()+" px"); }); //Return vertical scrollbar position $(selector). scrollTop() //Set vertical scrollbar position $(selector). scrollTop(position) Position : Optional. Specifies the new position in pixels $(selector).toggleClass(class,switch) Class : Required. Specifies one or more class names to add or remove. To specify several classes, separate the class names with a space.

removeClass() Removes one or more classes from selected Repeated(HTML elements Prop) Eg: $("button").click(function(){ $("p").removeClass("intro"); });

scrollLeft()

scrollTop()

toggleClass() Toggles between adding/removing one or Repeated(HTML more classes from selected elements Prop) Eg: $("button").click(function(){ $("p").toggleClass("main"); });

width()

Sets or returns the width of selected elements Eg: $("button").click(function(){ $("p").width(200); });

switch : Optional. A Boolean value specifying if the class should be added (true), or removed (false). $(selector).width() //Set height $(selector).width(value) Value : Required. Specifies the height in px, em, %, etc. Default unit is px //Set height using a function $(selector).width(function(index,oldwidth)) function(index, oldwidth) : Specifies a function that returns the new height of selected elements. ->index - Optional. Receives the index position of the selector -> oldwidth - Optional. Receives the current width of the selector

jQuery AJAX
jQuery has a rich library of methods (functions) for AJAX development. jQuery AJAX Example <html> <head> <script type="text/javascript"> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>

Result: Result before clicking change content button.

jQuery AJAX Example Let AJAX change this text Change Content(Button) Result: Result after clicking change content button. jQuery AJAX Example AJAX is not a programming language. It is just a technique for creating better and more interactive web applications. Change Content

What is AJAX? AJAX = Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. AJAX and jQuery jQuery provides a rich set of methods for AJAX web development. With jQuery AJAX, you can request TXT, HTML, XML or JSON data from a remote server using both HTTP Get and HTTP Post. And you can load remote data directly into selected HTML elements of your web page! Write Less, Do More The jQuery load() method is a simple (but very powerful) AJAX function. It has the following syntax: $(selector).load(url,data,callback) Use the selector to define the HTML element(s) to change, and the url parameter to specify a web address for your data. Only if you want to send data to the server, you need to use the data parameter. Only if you need to trigger a function after completion, you will use the callback parameter. Low Level AJAX $.ajax(options) is the syntax of the low level AJAX function. $.ajax offers more functionality than higher level functions like load, get, and post, but it is also more difficult to use. The option parameter takes name|value pairs defining url data, passwords, data types, filters, character sets, timeout and error functions. jQuery AJAX Methods AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page. The following table lists all the jQuery AJAX methods: Method $.ajax() Description Performs an AJAX request Syntax The ajax syntax is defined below after the table in detail. $(selector).ajaxComplete(function(event,xhr, options)) function(event,xhr,options : Required. Specifies the function to run when the request completes Additional parameters: ->event - contains the event object ->xhr - contains the XMLHttpRequest object ->options - contains the options used in the AJAX request $(selector).ajaxError(function(event,xhr,optio ns,exc)) function(event,xhr,options,exc) : Required. Specifies the function to run if the request

ajaxComplete() Specifies a function to run when the AJAX request completes Eg: $("#txt").ajaxStart(function(){ $("#wait").css("display","block"); }); $("#txt").ajaxComplete(function(){ $("#wait").css("display","none"); });

ajaxError()

Specifies a function to run when the AJAX request completes with an error Eg: $("div").ajaxError(function(){ alert("An error occurred!");

});

fails Additional parameters: ->event - contains the event object ->xhr - contains the XMLHttpRequest object ->options - contains the options used in the AJAX request ->exc - contains the JavaScript exception, if one occured $(selector).ajaxSend(function(event,xhr,optio ns)) function(event,xhr,options) : Required. Specifies the function to run if the request succeeds Additional parameters:] ->event - contains the event object ->xhr - contains the XMLHttpRequest object ->options - contains the options used in the AJAX request The ajaxSetup syntax is defined below after the ajex in detail. $(selector).ajaxStart(function()) function() : Required. Specifies the function to run when the AJAX request starts

ajaxSend()

Specifies a function to run before the AJAX request is sent Eg: $("div").ajaxSend(function(e,xhr,opt){ $(this).html("Requesting " + opt.url); });

$.ajaxSetup() ajaxStart()

Sets the default values for future AJAX requests Specifies a function to run when the first AJAX request begins Eg: $("div").ajaxStart(function(){ $(this).html("<img src='demo_wait.gif' />"); }); Specifies a function to run when all AJAX requests have completed Eg: $("div").ajaxStop(function(){ alert("All AJAX requests completed"); }); Specifies a function to run an AJAX request completes Successfully Eg: $("div").ajaxSuccess(function(){ alert("AJAX request successfully completed"); });

ajaxStop()

$(selector).ajaxStop(function()) function() : Required. Specifies the function to run when the AJAX request completed

ajaxSuccess()

$(selector).ajaxSuccess(function(event,xhr,o ptions)) function(event,xhr,options) : Required. Specifies the function to run if the request succeeds Additional parameters: ->event - contains the event object ->xhr - contains the XMLHttpRequest object ->options - contains the options used in the AJAX request

$.get() $.getJSON()

Loads data from a server using an AJAX HTTP get() syntax is defined below after the GET request ajexsetup in detail. Loads JSON-encoded data from a server using a HTTP GET Request Eg: $("button").click(function(){ $(selector).getJSON(url,data,success(data,sta tus,xhr))

url : Required. Specifies the url to send the request to data : Optional. Specifies data to be sent to $.getJSON("demo_ajax_json.js",function(res the server ult){ $.each(result, function(i, field){ success(data,status,xhr) : Optional. Specifies $("div").append(field + " "); the function to run if the request succeeds }); Additional parameters: }); ->data - contains the data returned from the

});

server. ->status - contains a string containing request status ("success", "notmodified", "error", "timeout", or "parsererror"). ->xhr - contains the XMLHttpRequest object

$.getScript()

Loads (and executes) a JavaScript from the a $(selector).getScript(url,success(response,sta server using an AJAX HTTP GET request tus)) Eg: $("button").click(function(){ url : Required. Specifies the url to send the $.getScript("demo_ajax_script.js"); request to }); success(response,status) : Optional. Specifies the function to run if the request succeeds Additional parameters: ->response - contains the result data from the request ->status - contains the status of the request ("success", "notmodified", "error", "timeout", or "parsererror")

load()

Loads data from a server and puts the returned HTML into the selected element Eg: $("button").click(function(){ $("div").load('demo_ajax_load.txt'); });

$(selector).load(url,data,function(response,st atus,xhr)) url : Required. Specifies the url to send the request to data : Optional. Specifies data to send to the server along with the request function(response,status,xhr) : Optional. Specifies the function to run when the request completes Additional parameters: ->response - contains the result data from the request ->status - contains the status of the request ("success", "notmodified", "error", "timeout", or "parsererror") ->xhr - contains the XMLHttpRequest object

$.param()

Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests) Eg: $("button").click(function(){ $("div").text($.param(personObj)); });

$.param(object,trad) object : Required. Specifies an array or object to serialize trad : Optional. A Boolean value specifying whether or not to use the traditional style of param serialization

$.post()

Loads data from a server using an AJAX HTTP $(selector).post(url,data,success(response,st POST request atus,xhr),dataType) Eg: $("input").keyup(function(){ url : Required. Specifies the url to send the txt=$("input").val(); request to $.post("demo_ajax_gethint.asp",{suggest:txt },function(result){ $("span").html(result); }); }); data: Optional. Specifies data to send to the server along with the request success(response,status,xhr): Optional. Specifies the function to run if the request

succeeds Additional parameters: ->response - contains the result data from the request ->status - contains the status of the request ("success", "notmodified", "error", "timeout", or "parsererror") ->xhr - contains the XMLHttpRequest object dataType : Optional. Specifies the data type expected of the server response. By default jQuery performs an automatic guess. Possible types: ->"xml" - An XML document ->"html" - HTML as plain text ->"text" - A plain text string ->"script" - Runs the response as JavaScript, and returns it as plain text ->"json" - Runs the response as JSON, and returns a JavaScript object ->"jsonp" - Loads in a JSON block using JSONP. Will add an "?callback=?" to the URL to specify the callback serialize() The serialize() method creates a URL $(selector).serialize() encoded text string by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request. Eg: $("button").click(function(){ $("div").text($("form").serialize()); }); serializeArray() The serializeArray() method creates an array $(selector).serializeArray() of objects (name and value) by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. Eg: $("button").click(function(){ x=$("form").serializeArray(); $.each(x, function(i, field){ $("#results").append(field.name + ":" + field.value + " "); }); });

jQuery AJAX ajax() Method


Example Change the text of a div element using an AJAX request: $("button").click(function(){

$.ajax({url:"demo_ajax_load.txt", success:function(result){ $("div").html(result); }}); });

Definition and Usage The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used. Syntax $.ajax({name:value, name:value, ... }) The parameters specifies one or more name/value pairs for the AJAX request. Possible names/values in the table below: Name async beforeSend(xhr) cache complete(xhr,status) contentType context data dataFilter(data,type) dataType error(xhr,status,error) global ifModified jsonp jsonpCallback password processData scriptCharset success(result,status,xhr) timeout traditional type url username xhr Value/Description A Boolean value indicating whether the request should be handled asynchronous or not. Default is true A function to run before the request is sent A Boolean value indicating whether the browser should cache the requested pages. Default is true A function to run when the request is finished (after success and error functions). The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded" Specifies the "this" value for all AJAX related callback functions Specifies data to be sent to the server A function used to handle the raw response data of the XMLHttpRequest The data type expected of the server response. A function to run if the request fails. A Boolean value specifying whether or not to trigger global AJAX event handles for the request. Default is true A Boolean value specifying whether a request is only successful if the response has changed since the last request. Default is: false. A string overriding the callback function in a jsonp request Specifies a name for the callback function in a jsonp request Specifies a password to be used in an HTTP access authentication request. A Boolean value specifying whether or not data sent with the request should be transformed into a query string. Default is true Specifies the charset for the request A function to be run when the request succeeds The local timeout (in milliseconds) for the request A Boolean value specifying whether or not to use the traditional style of param serialization Specifies the type of request. (GET or POST) Specifies the URL to send the request to. Default is the current page Specifies a username to be used in an HTTP access authentication request A function used for creating the XMLHttpRequest object

jQuery AJAX ajaxSetup() Method


Example Set the default URL and success function for all AJAX requests: $("button").click(function(){ $.ajaxSetup({url:"demo_ajax_load.txt",success:function(result){ $("div").html(result);}}); $.ajax(); });

Definition and Usage The ajaxSetup() method sets default values for future AJAX requests. Syntax $.ajaxSetup({name:value, name:value, ... }) The parameters specifies the settings for AJAX requests with one or more name/value pairs. Possible names/values in the table below: Note : The table for ajaxSetup name/value pair is same as the table for ajax name/value pair.Refer the name/value table abovefor the ajax.

jQuery AJAX get() Method


Example Change the text of a div element using an AJAX GET request: $("button").click(function(){ $.get("demo_ajax_load.txt", function(result){ $("div").html(result); }); });

Definition and Usage The get() method is used to perform an AJAX HTTP GET request. Syntax $(selector).get(url,data,success(response,status,xhr),dataType) Parameter url data Description Required. Specifies the url to send the request to Optional. Specifies data to send to the server along with the request

success(response,status,xhr) Optional. Specifies the function to run if the request succeeds Additional parameters: ->response - contains the result data from the request ->status - contains the status of the request ("success", "notmodified",

"error", "timeout", or "parsererror") ->xhr - contains the XMLHttpRequest object dataType Optional. Specifies the data type expected of the server response. By default jQuery performs an automatic guess. Possible types: ->"xml" - An XML document ->"html" - HTML as plain text ->"text" - A plain text string ->"script" - Runs the response as JavaScript, and returns it as plain text ->"json" - Runs the response as JSON, and returns a JavaScript object ->"jsonp" - Loads in a JSON block using JSONP. Will add an "?callback=?" to the URL to specify the callback

jQuery Miscellaneous Methods


jQuery Misc Methods Method data() Description Attaches data to, or gets data from, selected elements Eg: $("#btn1").click(function(){ $("div").data("greeting", "Hello World"); }); $("#btn2").click(function(){ alert($("div").data("greeting")); }); Syntax $(selector).data(name) Name : Optional. Specifies the name of data to retrieve. If no name is specified, this method will return all stored data for the element as an object

each()

Run a function for each element matched $(selector).each(function(index,element)) by the jQuery selector Eg: function(index,element) : Required. A $("button").click(function(){ function to run for each matched element. $("li").each(function(){ ->index - The index position of the alert($(this).text()) selector }); ->element - The current element (the }); "this" selector can also be used) Get the DOM elements matched by the selector Eg: $("button").click(function(){ x=$("p").get(0); $("div").text(x.nodeName + ": " + x.innerHTML); }); Search for a given element from among the matched elements Eg: $("li").click(function(){ alert($(this).index()); }); $(selector).get(index) index : Optional. Specifies which of the matching elements to get (by index number)

get()

index()

//Index of the first matched elemen relative to sibling elements. $(selector).index() //Index of the element relative to selector $(selector).index(element) Element : Optional. Specifies the element to get the index position of. Can be a DOM element or a jQuery selector

$.noConflict()

The noConflict() method releases jQuery's $.noConflict(removeAll) control of the $ variable. This method can also be used to specify a new custom removeAll : Optional. A Boolean value that name for the jQuery variable. specifies whether or not to release jQuery's control of ALL jQuery variables (including "jQuery") Tip: This method is useful when other JavaScript libraries use the $ for their functions. Use the noConflict() method to specify a new name for the jQuery variable: Eg: var jq=$.noConflict();

$.param() (Repeated in Ajax methods) removeData()

Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests) Removes a previously-stored piece of data Eg: $(selector).removeData(name) name : Optional. Specifies the name of

$("#btn2").click(function(){ $("div").removeData("greeting"); alert("Greeting is: " + $("div").data("greeting")); }); size() Return the number of DOM elements matched by the jQuery selector Eg: $("button").click(function(){ alert($("li").size()); }); Retrieve all the DOM elements contained in the jQuery set, as an array Eg: $("button").click(function(){ x=$("li").toArray() for (i=0;i<x.length;i++) { alert(x[i].innerHTML); } });

data to remove. If no name is specified, this method will remove all stored data from the selected elements $(selector).size()

toArray()

$(selector).toArray()

You might also like