• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/298

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

298 Cards in this Set

  • Front
  • Back
What is jQuery?
jQuery is a library of JavaScript Functions.

jQuery is a lightweight "write less, do more" JavaScript library.
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.
Where in an HTML document should <script> tag containing jQuery reference to library be stored
<script> tag should be inside the page's <head> section.
Where you can get jQuery? (2)
1)Download for jQuery.com
2)you can use the hosted jQuery library from Google or Microsoft
<head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> </head>
Demonstrates the jQuery hide() method, hiding the current HTML element.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$(this).hide();
}); }); </script> </head>
<body> <button>Click me</button>
</body> </html>
Demonstrates the jQuery hide() method, hiding the element with id="test".
<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>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>
Demonstrates the jQuery hide() method, hiding all elements with class="test".
<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>
<p>This is another paragraph.</p>
<button>Click me</button> </body> </html>
jQuery Syntax
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)
hides current element (syntax)

hides all paragraphs
$(this).hide()

$("p").hide()
hides all paragraphs with class="test"

hides the element with id="test"
$("p.test").hide()

$("#test").hide()
how you prevent all jQuery methods/code from running before the documents is finished loading
put jQuery inside a document.ready() function:

$(document).ready(function(){
// jQuery functions go here...
});
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
jQuery Selectors
jQuery selectors allow you to select HTML elements (or groups of elements) by element name, attribute name or by content.
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 all <p> elements 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
Query 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:

Example: $("p").css("background-color","yellow");
Select Current HTML element

Select all <p> elements with class="intro"
$(this)

$("p.intro")
Select all <p> elemets
Select all <h3> inside of <p>
Select all <p> elemets - $("p")
Select all <h3> inside of <p> - $("p .h3")
Select the first <p> element with id="intro"
Select all elements with class="intro"
Select the first element with id="intro"
Select the first <li> element of the first <ul>
$("p#intro:first")
$(".intro")
$("#intro")
$("ul li:first")
Select the first <li> element of every <ul>
Select all elements with an href attribute that ends with ".jpg"
$("ul li:first-child")
$("[href$='.jpg']")
Select all elements with class="head" inside a <div> element with id="intro"
$("div#intro .head")
jQuery Event Functions
jQuery Event Functions
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.
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.

<head> <script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="my_jquery_functions.js"></script> </head>
jQuery Name Conflicts (def)
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 Name Conflicts (example)
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var jq=jQuery.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>
jQuery Events
$(document).ready(function)
Binds a function to the ready event of a document
(when the document is finished loading)
jQuery Events
$(selector).click(function)

$(selector).dblclick(function)
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
jQuery Events
$(selector).focus(function)

$(selector).mouseover(function)
Triggers, or binds a function to the focus event of selected elements

Triggers, or binds a function to the mouseover event of selected elements
Demonstrates a simple jQuery hide() method hide each <p> as we click on it
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").click(function(){
$(this).hide(); }); });
</script> </head> <body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p> </body> </html>
jQuery multiple hide functions for different elemets
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").click(function(){
$(this).hide(); });
$("a").click(function(){
$(this).hide(); }); });
</script> </head> <body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p><a> WORK </a> </body> </html>
Another hide() demonstration. How to hide parts of text.
<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 spécialités</h3>
<div class="ex">
<button class="hide">Hide me</button>
<p>Contact: Marie Bertrand<br />
265, Boulevard Charonne<br />
Paris</p> </div> </body> </html>
Demonstrates a simple slide panel effect.
<!-- JQ --> $(document).ready(function(){
$(".flip").click(function(){
$(".panel").slideToggle("fast"); });});
<!-- CSS --> div.panel,p.flip { margin:0px;
padding:5px; text-align:center;
background:#e5eecc; border:solid 1px #c3c3c3; }
div.panel { height:120px;
display:none; }
<!-- HTML --> <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/Hide Panel</p>
</body> </html>
Demonstrates a simple jQuery fadeTo() method.
<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>
Demonstrates a simple jQuery animate() method.
<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;height:100px;width:100px;position:relative"> </div> </body> </html>
jQuery Hide and Show

With jQuery, you can hide and show HTML elements with the hide() and show() methods:
$("#hide").click(function(){
$("p").hide(); });
$("#show").click(function(){
$("p").show(); });
jQuery Hide and Show

With jQuery, you can hide and show HTML elements with the hide() and show() methods (full code):
<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 the two optional parameters: speed and callback.
$(selector).hide(speed,callback)

$(selector).show(speed,callback)

The speed parameter specifies the speed of the hiding/showing, and can take the following values: "slow", "fast", "normal", or milliseconds.
The callback parameter is the name of a function to be executed after the hide (or show) function completes. You will learn more about the callback parameter in the next chapter of this tutorial.
jQuery Toggle (expl)
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,callback)
The speed parameter can take the following values: "slow", "fast", "normal", or milliseconds.
jQuery Toggle (code)
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").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>
jQuery Slide - slideDown, slideUp, slideToggle (expl)
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(speed,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
<!-- JQ --> $(document).ready(function(){
$(".flip").click(function(){
$(".panel").slideDown("slow"); }); });
<!-- CSS --> div.panel,p.flip { margin:0px; padding:5px;
text-align:center; background:#e5eecc;
border:solid 1px #c3c3c3; }
div.panel { height:120px; display:none; } ...
<!-- HTML --> <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
<!-- JQ --> $(document).ready(function(){
$(".flip").click(function(){
$(".panel").slideUp("slow"); }); }); </script>
<!-- CSS --> div.panel,p.flip { margin:0px;
padding:5px; text-align:center;
background:#e5eecc;
border:solid 1px #c3c3c3; }
div.panel { height:120px; }
<!-- HTML --> <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">Hide Panel</p> </body> </html>
slideToggle() Example
<!-- JQ --> $(document).ready(function(){
$(".flip").click(function(){
$(".panel").slideToggle("slow"); });});
<!-- CSS --> div.panel,p.flip { margin:0px; padding:5px; text-align:center;
background:#e5eecc; border:solid 1px #c3c3c3; }
div.panel { height:120px; display:none; }
<!-- HTML --> <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/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,opacity,callback)

The speed parameter can take the following values: "slow", "fast", "normal", or milliseconds.
The opacity parameter in the fadeTo() method allows fading to 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(){
$("div").click(function(){
$(this).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],[callback])
The key parameter is params. It defines the CSS properties that will be animated. Many properties can be animated at the same time
jQuery Custom Animations (src)
<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;height:100px;width:200px;position:relative">HELLO</div> </body> </html>
jQuery Callback Functions
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.
A callback function is executed after the current animation (effect) is finished.
jQuery Callback Example (expl)
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");
});
jQuery Callback Example (code)
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").hide(1000,function(){
alert("The paragraph is now hidden");
}); }); });
</script> </head> <body>
<button>Hide</button>
<p>This is a paragraph with little content.</p>
</body> </html>
Changing HTML Content (Expl)
The html() method changes the contents (innerHTML) of matching HTML elements.

Example
$("p").html("W3Schools");
Changing HTML Content (code)
<!-- JQ --> $(document).ready(function(){
$("button").click(function(){
$("p").html("W3Schools");
}); }); </script> </head> <body>
<!-- CSS -->
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button> </body> </html>
Adding HTML content (expl)
append and preappend
Adding HTML content
$(selector).append(content)/$(selector).prepend(content)

The append() method appends content to the inside of matching HTML elements.
The prepend() method "prepends" content to the inside of matching HTML elements.
Example: $("p").append(" W3Schools");
Adding HTML content (code)
<!-- JQ > $(document).ready(function(){
$("button").click(function(){
$("p").append(" <b>W3Schools</b>."); }); });
<!-- HTML --> <h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
$(selector).after(content)
$(selector).before(content)
The after() method inserts HTML content after all matching elements.
The before() method inserts HTML content before all matching elements.
$(selector).after(content) full example
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").after(" W3Schools.");
});
});
</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>
jQuery css() Method
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 (expl)
Use css(name) to return the specified CSS property value of the FIRST matched element:

Example
$(this).css("background-color");
Return CSS Property (code)
<!-- JQ --> $(document).ready(function(){
$("div").click(function(){
$("p").html($(this).css("background-color")); }); });
<!-- HTML --> <div style="width:100px;height:100px;background:#ff0000"></div> <p>Click in the red box to return the background color.</p>
Set CSS Property and Value (expl)
Use css(name,value) to set the specified CSS property for ALL matched elements:

Example: $("p").css("background-color","yellow");
Set CSS Property and Value (code)
<!-- JQ --> $(document).ready(function(){
$("button").click(function(){
$("p").css("background-color","yellow"); }); });
<!-- HTML --> <h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
Set Multiple CSS Property/Value Pairs (code)
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").css({"background-color":"yellow","font-size":"200%"});
});
});
</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>
jQuery height() and width() Methods
jQuery height() and width() Methods
jQuery has two important methods for size manipulation.
------------------------------------------------------------------------------------
height() + width() Size Manipulation Examples
------------------------------------------------------------------------------------
The height() method sets the height of all matching elements:
$("#div1").height("200px");
The width() method sets the width of all matching elements:
$("#div2").width("300px");
jQuery height() (expl)
<!-- JQ --> $(document).ready(function(){
$("button").click(function(){
$("#div1").height("200px"); }); });
<!-- HTML --> <div id="div1" style="background:yellow;height:100px;width:100px">HELLO</div>
<div style="background:yellow;height:100px;width:100px">W3SCHOOLS</div>
<button>Click me</button>
jQuery width() (expl)
<!-- JQ --> $(document).ready(function(){
$("button").click(function(){
$("#div2").width("300px"); }); });
<!-- HTML --> <div style="background:yellow;height:100px;width:100px">HELLO</div>
<div id="div2" style="background:yellow;height:100px;width:100px">W3SCHOOLS</div>
<button>Click me</button> </body> </html>
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!
jQuery load()
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
jQuery load() (code)
<!-- JQ --> $(document).ready(function(){
$("button").click(function(){
$("div").load('test1.txt'); }); });
<!-- HTML --> <div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button>
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.
Low Level AJAX (code)
<!-- JQ --> $(document).ready(function(){
$("button").click(function(){
$.ajax({url:"test1.txt", success:function(result){
$("div").html(result); }}); });});
<!-- HTML --> <div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button>
$(selector).load(url,data,callback)

$.ajax(options)
Load remote data into selected elements

Load remote data into an XMLHttpRequest object
All elements
$("*")

$(document).ready(function(){
$("body *").css("background-color","red");
});
All elements with class="intro"
$(".intro")
-------------
$(document).ready(function(){
$(".intro").css("background-color","red");
});
-------------
<p class="intro">My name is Donald</p>
jQuery .(dot) Selector
Definition and Usage
The . selector selects elements with a specific class.
The class refers to the class attribute of a HTML element.
Unlike the id attribute, the class attribute is most often used on several elements.
This allows you to set a particular style for any HTML elements with the same class.
Syntax: $(".class")
select all elements with the classes "intro" and "demo"

select all p elements

select all animated elements
$(".intro.demo")

$("p")

$(":animated")
select the first p element
select the last p element
select all the even tr elements
select all the odd tr elements
:first $("p:first")
:last $("p:last")
:even $("tr:even")
:odd $("tr:odd")
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
$("ul li:eq(3)")

$("ul li:gt(3)")

$("ul li:lt(3)")
select all input elements that are not empty

select all header elements h1, h2 ...
$("input:not(:empty)")

$(":header")
jQuery animate() - Manipulate Multiple Properties
$("button").click(function(){
$("div").animate({
left:'250px',
opacity:'0.5',
height:'150px',
width:'150px'
}); });

important thing to remember: all property names must be camel-cased when used with the animate() method: You will need to write paddingLeft instead of padding-left, marginRight instead of margin-right, and so on.
select all elements which contains the text

select all elements with no child (elements) nodes

select all visible tables
$(":contains('W3Schools')")

$(":empty")

$("table:visible")
select elements with a href attribute
$("[href]")
select elements with a href attribute value equal to "default.htm"

select all elements with a href attribute value not equal to "default.htm"
$("[href='default.htm']")

$("[href!='default.htm']")
select all elements with a href attribute value ending with ".jpg"

select input elements
$("[href$='.jpg']")

$(":input")
select all elements with type="text"

select all input elemets type password
select all elements with type="text": $(":text")

select all input elemets type password: $(":text")
select all input elements with type="button"

select all input elements with type="image"

select all input elements with type="file"

select all enabled input elements
$(":button")

$(":image")

$(":file")

$(":enabled")
select all disabled input elements

select all selected input elements

select all checked input ements
$(":disabled")

$(":selected")

$(":checked")
jQuery Event bind() Method
The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the events occur.

$(selector).bind(event,data,function)
jQuery Event blur() Method
The blur event occurs when an element loses focus.
The blur() method triggers the blur event, or specifies a function to run when a blur event occurs.
Tip: In newer browsers, the blur event can be used on all elements (not only form elements).

$(selector).blur()
Change background color of an input field when it loses focus (blur):
$(document).ready(function(){
$("input").focus(function(){
$("input").css("background-color","#FFFFCC"); });
$("input").blur(function(){
$("input").css("background-color","#D6D6FF"); }); });
--------------------------
<input type="text" />
<p>Click in the input field to get focus, and outside the input field to lose focus (blur).</p>
jQuery Event change() Method
The change event occurs when the value of an element is changed (only works on text fields, text areas and select elements).

The change() method triggers the change event, or specifies a function to run when a change event occurs.

$(".field").change(function(){
$(this).css("background-color","#FFFFCC");
});
jQuery Event click() Method definition and usage
The click event occurs when an element is clicked.
The click() method triggers the click event, or specifies a function to run when a click event occurs.
Trigger the click event for the selected elements.

Syntax: $(selector).click()
Bind a Function to the click Event
<!-- JQ -->
$(document).ready(function(){
$("button").click(function(){
$("p").slideToggle(); }); });
<!-- HTML --> <p>This is a paragraph.</p>
<button>Click me!</button>
</body></html>
Trigger the dblclick Event code
<!-- JQ --> $(document).ready(function(){
$("button").dblclick(function(){
$("p").slideToggle(); });
$("p").click(function(){
$("button").dblclick(); }); });
<!-- HTML --> <button>Double-click to toggle</button>
<p>Click this paragraph to trigger the dblclick event for the button.</p></body></html>
Bind a Function to the dblclick Event code
<!-- JQ --> $(document).ready(function(){
$("button").dblclick(function(){
$("p").slideToggle(); }); });
<!-- HTML --> <p>This is a paragraph.</p>
<button>Double-click me!</button>
jQuery Event delegate() Method Definition and Usage
The delegate() method attaches one or more event handlers for specified elements that are children of selected elements, and specifies a function to run when the events occur.
Event handlers attached using the delegate() method will work for both current and FUTURE elements (like a new element created by a script).
$(selector).delegate(childSelector,event,data,function)
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
delegate code example
<!-- JQ --> $(document).ready(function(){
$("div").delegate("button","click",function(){
$("p").slideToggle(); }); });
<!-- HTML --> <div style="background-color:yellow">
<p>This is a paragraph.</p>
<button>Click me!</button>
jQuery Event die() Method Definition and Usage
The die() method removes one or more event handlers, added with the live() method, for selected elements.

Syntax: $(selector).die(event,function)
die() example
<!-- JQ --> $(document).ready(function(){
$("p").live("click",function(){
$(this).slideToggle(); });
$("button").click(function(){
$("p").die(); }); });
<!-- HTML -->
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>Click any p element to make it disappear. Including this one.</p>
<button>Remove event handlers, added with the live() method, for p elements</button>
</body> </html>
jQuery Event error() Method definition and usage
The error event occurs when an element encounters an error (if the element is not loaded correctly).
The error() method triggers the error event, or specifies a function to run when an error event occurs.
Tip: This method is a shortcut for bind('error', handler).

Trigger the error event for the selected elements.
Syntax: $(selector).error()
Bind a Function to the error Event short
$(selector).error(function)
triger and error event (code)
<!-- JQ --> $(document).ready(function(){
$("img").error(function(){
$("img").replaceWith("<p>Error loading image!</p>"); });
$("button").click(function(){
$("img").error(); }); });
<!-- HTML --> <img src="img_pulpitrock.jpg" alt="Pulpit rock" width="284" height="213" />
<br />
<button>Trigger error event for the image</button>
</body> </html>
The current DOM element within the event bubbling phase
event.currentTarget
jQuery Event pageX() Property (code)
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).mousemove(function(e){
$("span").text("X: " + e.pageX + ", Y: " + e.pageY);
}); }); </script> </head> <body>
<p>The mouse is at: <span></span></p>
</body> </html>
jQuery Event preventDefault() Method Definition and Usage

The preventDefault() method stops the default action of an element from happening (for example, preventing a form being submitted when a submit button is clicked).
<!-- JQ --> $(document).ready(function(){
$("a").click(function(event){
event.preventDefault(); }); });
<!-- HTML --> <a href="http://w3schools.com/">Go to W3Schools.com</a>
<p>The preventDefault() method will prevent the link above from following the URL.</p>
</body> </html>
jQuery Event isDefaultPrevented() Method Definition and Usage

The isDefaultPrevented() method returns whether or not the preventDefault() method is called for the specified event object. (code)
<!-- JQ --> $(document).ready(function(){
$("a").click(function(event){
event.preventDefault();
  alert("Default prevented: " + event.isDefaultPrevented());
}); });
<!-- HTML --> <a href="http://w3schools.com/">Go to W3Schools.com</a>
<p>The preventDefault() method will prevent the link above from following the URL.</p>
<p>Click the link and check if the default action is prevented.</p>
jQuery Event result Property
--------------------------------------
Definition and Usage

The result property contains the last value returned by an event handler function that was triggered by the specified event. (code)
<!-- JQ --> $("button").click(function(e) {
return ("For the last click, the mouse position was: X" +e.pageX + ", Y" + e.pageY); });
$("button").click(function(e) {
$("p").html(e.result); }); });
<!-- HTML --> <p>This is a paragraph.</p>
<button>Click me</button>
</body> </html>
jQuery Event target Property
--------------------------------------
Definition and Usage

The target property specifies which DOM element triggered the event. (code)
<!-- JQ --> $(document).ready(function(){
$("p, button, h1, h2").click(function(event){
$("div").html("Triggered by a " + event.target.nodeName + " element."); }); });
<!-- HTML -->
<h1>This is a heading</h1>
<h2>This is another heading</h2>
<p>This is a paragraph</p>
<button>This is a button</button>
<p>The headings, paragraphs and button element has a click defined.<br />If you trigger one of the events, the div below will tell you which element triggered the event.</p> <div /> </body> </html>
jQuery Event timeStamp Property
-----------------------------------
Definition and Usage

The timeStamp property contains the number of milliseconds since January 1 1970, for when the event is triggered. (code)
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(e){
$("span").text(e.timeStamp);
}); });
</script> </head> <body>
<p>The click event for the button below occurred <span>unknown</span> milliseconds after January 1, 1970.</p> <button>Click me</button> </body> </html>
jQuery Event type Property
------------------------------------
Definition and Usage
The type property specifies which event type was triggered.
<!-- JQ --> $(document).ready(function(){
$("p").bind('click dblclick mouseover mouseout',function(event){
$("div").html("Event: " + event.type); }); });
<!-- HTML -->
<p>This paragraph has a click, double-click, mouseover and mouseout event defined.<br />If you trigger one of the events, the div below will display the event type.</p>
<div /> </body> </html>
jQuery Event which Property
-------------------------------------
Definition and Usage
The which property specifies which key or button was pressed for the event.
This property can be used on key and button events.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").keydown(function(event){
$("div").html("Key: " + event.which);
}); });
</script> </head> <body>
Enter your name: <input type="text" />
<p>When you type in the field above, the div below will display the key number.</p>
<div /> </body> </html>
jQuery Event focus() Method
--------------------------------------
Definition and Usage

The focus event occurs when an element gets focus (when selected by a mouse click or by "tab-navigating" to it).

The focus() method triggers the focus event, or specifies a function to run when a focus event occurs.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").focus(function(){
$("input").css("background-color","#FFFFCC"); });
$("input").blur(function(){
$("input").css("background-color","#D6D6FF"); }); });
</script> </head> <body>
Enter your name: <input type="text" />
<p>Click in the input field to get focus, and outside the input field to lose focus (blur).</p>
</body> </html>
jQuery Event focusin() Method
-----------------------------
The focusin event occurs when an element gets focus (when selected by a mouse click or by "tab-navigating" to it).
The focusin() method specifies a function to run when a focusin event occurs on any child element of the selected elements.
Unlike the focus() method, the focusin() method triggers if any child element gets focus.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div").focusin(function(){
$(this).css("background-color","#FFFFCC"); }); });
</script> </head> <body>
<div style="border: 1px solid black;padding:10px;">
First name: <input type="text" /><br />
Last name: <input type="text" /> </div>
<p>Click in the input field to get focus.</p> </body> </html>
jQuery Event focusout() Method
--------------------------------
The focusout event occurs when an element loses focus.
The focusout() method specifies a function to run when a focusout event occurs on any child element of the selected elements.
Unlike the blur() method, the focusout() method triggers if any child element loses focus.
<html> <head> <script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div").focusin(function(){
$(this).css("background-color","#FFFFCC"); });
$("div").focusout(function(){
$(this).css("background-color","#FFFFFF"); }); });
</script> </head> <body>
<div style="border: 1px solid black;padding:10px;">
First name: <input type="text" /><br />
Last name: <input type="text" /></div>
<p>Click outside the div to lose focus (blur).</p> </body> </html>
jQuery Event hover() Method
--------------------------------------
The hover() method binds functions to the mouseenter and mouseleave events.
<html> <head> <script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").hover(function(){
$("p").css("background-color","yellow");
},function(){
$("p").css("background-color","#E9E9E4"); }); });
</script> </head> <body>
<p style="background-color:#E9E9E4">Hover the mouse pointer over this paragraph.</p>
</body> </html>
jQuery Event keydown() Method
--------------------------------
A key press has two parts: 1. The key is pressed down. 2. The key is released.
The keydown event occurs when a keyboard key is pressed down.
The keydown() method triggers the keydown event, or specifies a function to run when a keydown event occurs.
Tip: Use the event.which property to return which key was pressed.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").keydown(function(){
$("input").css("background-color","#FFFFCC"); });
$("input").keyup(function(){
$("input").css("background-color","#D6D6FF"); }); });
</script> </head> <body>
Enter your name: <input type="text" />
<p>Enter your name in the input field above. It will change background color on keydown and keyup.</p>
</body> </html>
jQuery Event keypress() Method
---------------------------------
Definition and Usage

The keypress event is similar to the keydown event. The event occurs when a button is pressed down. It occurs on the element that currently has focus.

However, unlike the keydown event, the keypress event occurs for each inserted character.

The keypress() method triggers the blur event, or if the function parameter is set, it specifies what happens when a keypress event occurs.

Note: If set on the document element, the event will occur no matter what element has focus.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
i=0;
$(document).ready(function(){
$("input").keypress(function(){
$("span").text(i+=1);
}); });
</script> </head> <body>
Enter your name: <input type="text" />
<p>Keypresses:<span>0</span></p>
</body> </html>
jQuery Event live() Method
------------------------------------
Definition and Usage

The live() method attaches one or more event handlers for selected elements, and specifies a function to run when the events occur.

Event handlers attached using the live() method will work for both current and FUTURE elements matching the selector (like a new element created by a script).
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").live("click",function(){
$("p").slideToggle();
}); });
</script> </head> <body>
<p>This is a paragraph.</p>
<button>Click me!</button>
</body> </html>
jQuery Event load() Method
-------------------------------------
Definition and Usage

The load() event occurs when a specified element (and sub elements) has been loaded.

This event works with any element with an URL (like image, script, frame, iframe).

Depending on the browser, the load event may not trigger if the image is cached (Firefox and IE).

Note: There is also a jQuery Ajax method called load. Which one is called, depends on the parameters
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("img").load(function(){
$("div").text("Image loaded");
}); });
</script> </head> <body>
<img src="img_moustiers-sainte-marie.jpg" alt="Cinqueterra" width="304" height="236" />
<div>Image is currently loading.</div>
<p><b>Note:</b> Depending on the browser, the load event may not trigger if the image is cached.</p>
</body> </html>
jQuery Event type Property
------------------------------------
Definition and Usage
The type property specifies which event type was triggered.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").bind('click dblclick mouseover mouseout',function(event){
$("div").html("Event: " + event.type);
});
});
</script> </head> <body>
<p>This paragraph has a click, double-click, mouseover and mouseout event defined.<br />If you trigger one of the events, the div below will display the event type.</p>
<div /> </body> </html>
jQuery Event which Property
-------------------------------------
Definition and Usage
The which property specifies which key or button was pressed for the event.
This property can be used on key and button events.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").keydown(function(event){
$("div").html("Key: " + event.which);
}); });
</script> </head> <body>
Enter your name: <input type="text" />
<p>When you type in the field above, the div below will display the key number.</p>
<div /> </body> </html>
jQuery Event focus() Method
--------------------------------------
Definition and Usage

The focus event occurs when an element gets focus (when selected by a mouse click or by "tab-navigating" to it).

The focus() method triggers the focus event, or specifies a function to run when a focus event occurs.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").focus(function(){
$("input").css("background-color","#FFFFCC");
});
$("input").blur(function(){
$("input").css("background-color","#D6D6FF");
}); });
</script> </head> <body>
Enter your name: <input type="text" />
<p>Click in the input field to get focus, and outside the input field to lose focus (blur).</p>
</body> </html>
jQuery Event focusin() Method
-----------------------------
Definition and Usage

The focusin event occurs when an element gets focus (when selected by a mouse click or by "tab-navigating" to it).

The focusin() method specifies a function to run when a focusin event occurs on any child element of the selected elements.

Unlike the focus() method, the focusin() method triggers if any child element gets focus.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div").focusin(function(){
$(this).css("background-color","#FFFFCC");
}); });
</script> </head> <body>
<div style="border: 1px solid black;padding:10px;">
First name: <input type="text" /><br />
Last name: <input type="text" /> </div>
<p>Click in the input field to get focus.</p> </body> </html>
jQuery Event focusout() Method
--------------------------------
Definition and Usage

The focusout event occurs when an element loses focus.

The focusout() method specifies a function to run when a focusout event occurs on any child element of the selected elements.

Unlike the blur() method, the focusout() method triggers if any child element loses focus.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div").focusin(function(){
$(this).css("background-color","#FFFFCC");
});
$("div").focusout(function(){
$(this).css("background-color","#FFFFFF");
}); });
</script> </head> <body>
<div style="border: 1px solid black;padding:10px;">
First name: <input type="text" /><br />
Last name: <input type="text" /></div>
<p>Click outside the div to lose focus (blur).</p> </body> </html>
jQuery Event hover() Method
--------------------------------------
Definition and Usage

The hover() method binds functions to the mouseenter and mouseleave events.
<html> <head> <script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").hover(function(){
$("p").css("background-color","yellow");
},function(){
$("p").css("background-color","#E9E9E4");
}); });
</script> </head> <body>
<p style="background-color:#E9E9E4">Hover the mouse pointer over this paragraph.</p>
</body> </html>
jQuery Event keydown() Method
--------------------------------
Definition and Usage

A key press has two parts: 1. The key is pressed down. 2. The key is released.

The keydown event occurs when a keyboard key is pressed down.

The keydown() method triggers the keydown event, or specifies a function to run when a keydown event occurs.

Tip: Use the event.which property to return which key was pressed.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").keydown(function(){
$("input").css("background-color","#FFFFCC");
});
$("input").keyup(function(){
$("input").css("background-color","#D6D6FF");
}); });
</script> </head> <body>
Enter your name: <input type="text" />
<p>Enter your name in the input field above. It will change background color on keydown and keyup.</p>
</body> </html>
jQuery Event keypress() Method
---------------------------------
Definition and Usage

The keypress event is similar to the keydown event. The event occurs when a button is pressed down. It occurs on the element that currently has focus.

However, unlike the keydown event, the keypress event occurs for each inserted character.

The keypress() method triggers the blur event, or if the function parameter is set, it specifies what happens when a keypress event occurs.

Note: If set on the document element, the event will occur no matter what element has focus.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
i=0;
$(document).ready(function(){
$("input").keypress(function(){
$("span").text(i+=1);
}); });
</script> </head> <body>
Enter your name: <input type="text" />
<p>Keypresses:<span>0</span></p>
</body> </html>
jQuery Event live() Method
------------------------------------
Definition and Usage

The live() method attaches one or more event handlers for selected elements, and specifies a function to run when the events occur.

Event handlers attached using the live() method will work for both current and FUTURE elements matching the selector (like a new element created by a script).
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").live("click",function(){
$("p").slideToggle();
}); });
</script> </head> <body>
<p>This is a paragraph.</p>
<button>Click me!</button>
</body> </html>
jQuery Event load() Method
-------------------------------------
Definition and Usage

The load() event occurs when a specified element (and sub elements) has been loaded.

This event works with any element with an URL (like image, script, frame, iframe).

Depending on the browser, the load event may not trigger if the image is cached (Firefox and IE).

Note: There is also a jQuery Ajax method called load. Which one is called, depends on the parameters
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("img").load(function(){
$("div").text("Image loaded");
}); });
</script> </head> <body>
<img src="img_moustiers-sainte-marie.jpg" alt="Cinqueterra" width="304" height="236" />
<div>Image is currently loading.</div>
<p><b>Note:</b> Depending on the browser, the load event may not trigger if the image is cached.</p>
</body> </html>
jQuery Event mousedown() Method
----------------------------
Definition and Usage

The mousedown event occurs when the mouse pointer is over an element, and the mouse button is pressed down.

Unlike the click event, the mousedown event only requires the button to be pressed down, not released.

The mousedown() method triggers the mousedown event, or if the function parameter is set, it specifies what happens when a mousedown event occurs.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").mousedown(function(){
$("p").slideToggle();
}); });
</script> </head> <body>
<p>This is a paragraph.</p>
<button>Toggle</button> </body> </html>
jQuery Event mouseenter() Method
------------------------------
Definition and Usage

The mouseenter event occurs when the mouse pointer is over an element.

This event is mostly used together with the mouseleave event.

The mouseenter() method triggers the mouseenter event, or if the function parameter is set, it specifies what happens when a mouseenter event occurs.

Note: Unlike the mouseover event, the mouseenter event only triggers when the the mouse pointer enters the selected element. The mouseover event is triggered if a mouse pointer enters any child elements as well. See the example at the end of the page for a demonstration.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").mouseenter(function(){
$("p").css("background-color","yellow");
});
$("p").mouseleave(function(){
$("p").css("background-color","#E9E9E4");
}); });
</script> </head> <body>
<p style="background-color:#E9E9E4">Hover the mouse pointer over this paragraph.</p>
</body> </html>
jQuery Event mouseleave() Method
------------------------------------
Definition and Usage

The mouseleave event occurs when the mouse pointer leaves an element.

This event is mostly used together with the mouseenter event.

The mouseleave() method triggers the mouseleave event, or if the function parameter is set, it specifies what happens when a mouseleave event occurs.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").mouseenter(function(){
$("p").css("background-color","yellow");
});
$("p").mouseleave(function(){
$("p").css("background-color","#E9E9E4");
}); });
</script> </head> <body>
<p style="background-color:#E9E9E4">Hover the mouse pointer over this paragraph.</p>
</body> </html>
jQuery Event mousemove() Method
------------------------------------
Definition and Usage

The mousemove event occurs whenever the mouse pointer moves within a specified element.

The mousemove() method triggers the mousemove event, or if the function parameter is set, it specifies what happens when a mousemove event occurs.

Note: Each time a user moves the mouse one pixel, a mousemove event occurs. It takes system resources to process all mousemove events. Use this event carefully.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).mousemove(function(e){
$("span").text(e.pageX + ", " + e.pageY);
}); });
</script> </head> <body>
<p>Mouse is at coordinates: <span></span>.</p>
</body> </html>
jQuery Event mouseout() Method
----------------------------------
Definition and Usage

The mouseout event occurs when the mouse pointer is removed from an element.

This event is mostly used together with the mouseover event.

The mouseout() method triggers the mouseout event, or if the function parameter is set, it specifies what happens when a mouseout event occurs.

Note: Unlike the mouseleave event, the mouseout event is triggered if a mouse pointer leaves any child elements as well as the selected element. The mouseleave event only triggers when the the mouse pointer leaves the selected element. See the example at the end of the page for a demonstration.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").mouseover(function(){
$("p").css("background-color","yellow");
});
$("p").mouseout(function(){
$("p").css("background-color","#E9E9E4");
}); });
</script> </head> <body>
<p style="background-color:#E9E9E4">Hover the mouse pointer over this paragraph.</p>
</body> </html>
jQuery Event mouseover() Method
-----------------------------------
Definition and Usage

The mouseover event occurs when the mouse pointer is over an element.

This event is mostly used together with the mouseout event.

The mouseover() method triggers the mouseover event, or if the function parameter is set, it specifies what happens when a mouseover event occurs.

Note: Unlike the mouseenter event, the mouseover event triggers if a mouse pointer enters any child elements as well as the selected element. The mouseenter event is only triggered when the the mouse pointer enters the selected element. See the example at the end of the page for a demonstration.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").mouseover(function(){
$("p").css("background-color","yellow");
});
$("p").mouseout(function(){
$("p").css("background-color","#E9E9E4");
}); });
</script> </head> <body>
<p style="background-color:#E9E9E4">Hover the mouse pointer over this paragraph.</p>
</body> </html>
jQuery Event mouseup() Method
--------------------------------
Definition and Usage

The mouseup event occurs when the mouse pointer is released over an element.

Unlike the click event, the mouseup event only requires the button to be released. It will be triggered on the element the mouse pointer is over when the button is released.

The mouseup() method triggers the mouseup event, or if the function parameter is set, it specifies what happens when a mouseup event occurs.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").mouseup(function(){
$("p").slideToggle();
}); });
</script> </head> <body>
<p>This is a paragraph.</p>
<button>Toggle</button> </body> </html>
jQuery Event one() Method
------------------------------------
Definition and Usage

The one() method attaches one or more event handlers for selected elements, and specifies a function to run when the events occur.

When using the one() method, the event handler function is only run ONCE for each element.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").one("click",function(){
$(this).animate({fontSize:"+=6px"});
}); });
</script> </head> <body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>Click any p element to increase its text size. The event will only trigger once for each p element.</p> </body> </html>
jQuery Event ready() Method
-------------------------------------
Definition and Usage

The ready event occurs when the DOM (document object model) has been loaded, and the page has been completely rendered (including images).

Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above.
The ready() method specifies what happens when a ready event occurs.
The ready() method can only be used on the current document, so no selector is required.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").slideToggle();
}); });
</script> </head> <body>
<p>This is a paragraph.</p>
<button>Toggle between slide up and slide down for a p element</button>
</body> </html>
jQuery Event resize() Method
---------------------------------------
Definition and Usage

The resize event occurs when the browser window changes size.

The resize() method triggers the resize event, or if the function parameter is set, it specifies what happens when a resize event occurs.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
x=0;
$(document).ready(function(){
$(window).resize(function() {
$("span").text(x+=1);
}); });
</script> </head> <body>
<p>Window resized <span>0</span> times.</p>
<p>Try resizing your browser window.</p> </body> </html>
jQuery Event scroll() Method
-------------------------------------
Definition and Usage

The scroll event occurs when the user scrolls in the specified element.

The scroll event works for all scrollable elements and the window object (browser window).

The scroll() method triggers the scroll event, or if the function parameter is set, it specifies what happens when a scroll event occurs.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
x=0;
$(document).ready(function(){
$("div").scroll(function() {
$("span").text(x+=1);
}); });
</script> </head> <body>
<p>Try the scroll in the div</p>
<div style="width:200px;height:100px;overflow:scroll;">In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
<br /><br />
'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'</div>
<p>Scrolled <span>0</span> times.</p> </body> </html>
jQuery Event select() Method
---------------------------------------
Definition and Usage

The select event occurs when the text is selected (marked) in a text area or text input element.

The select() method triggers the select event, or if the function parameter is set, it specifies what happens when a select event occurs.
<html> <head> <script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").select(function(){
$("input").after(" Text marked!");
}); });
</script> </head> <body>
<input type="text" name="FirstName" value="Hello World" />
<p>Try to select the text inside the input field, and see what happens.</p>
</body> </html>
jQuery Event submit() Method
--------------------------------------
Definition and Usage

The submit event occurs when a form is submitted.

This event can only be be used on form elements.

The submit() method triggers the submit event, or if the function parameter is set, it specifies what happens when a submit event occurs.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("form").submit(function(e){
alert("Submitted");
}); });
</script> </head> <body>
<form name="input" action="" method="get"> First name:
<input type="text" name="FirstName" value="Mickey" size="20">
<br />Last name: <input type="text" name="LastName" value="Mouse" size="20">
<br /> <input type="submit" value="Submit">
</form> </body> </html>
jQuery Event toggle() Method
---------------------------------------
Definition and Usage

The toggle() method is used to bind two or more event handler functions to toggle between for the click event for selected elements.

This method can also be used to toggle between hide() and show() for the selected elements.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").toggle(function(){
$("body").css("background-color","green");},
function(){
$("body").css("background-color","red");},
function(){
$("body").css("background-color","yellow");}
); });
</script> </head> <body>
<p>Click me to toggle between different background colors.</p>
</body> </html>
jQuery Event trigger() Method
---------------------------------------
Definition and Usage

The trigger() method triggers specified event types for selected elements.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").select(function(){
$("input").after(" Text marked!"); });
$("button").click(function(){
$("input").trigger("select"); }); });
</script> </head> <body>
<input type="text" name="FirstName" value="Hello World" /> <br />
<button>Activate the select event for the input field.</button>
</body> </html>
jQuery Event triggerHandler() Method
--------------------------------------
Definition and Usage

The triggerHandler() method triggers specified event types for selected element.

The triggerHandler() method is similar to the trigger() method. Except that it does not trigger the default behavior of an event (like form submission) and it only affects the first matched element.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").select(function(){
$("input").after(" Input select event occured!"); });
$("button").click(function(){
$("input").triggerHandler("select"); }); });
</script> </head> <body>
<input type="text" name="FirstName" value="Hello World" /> <br />
<button>Activate the select event for the input field.</button>
<p>Notice that, unlike the trigger() method, the triggerHandler() method does not cause the default behavior of the event to occur (The text is not marked).</p> </body> </html>
jQuery Event unbind() Method
---------------------------------
Definition and Usage

The unbind() method removes event handles from selected elements.

This method can remove all or selected event handlers, or stop specified functions from running when the event occurs.

The unbind() method works on any event handler attached with jQuery.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").click(function(){
$(this).slideToggle();
});
$("button").click(function(){
$("p").unbind();
}); });
</script> </head> <body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>Click any p element to make it disappear. Including this one.</p>
<button>Remove event handlers for p elements</button>
</body> </html>
jQuery Event undelegate() Method
-----------------------------------
Definition and Usage

The undelegate() method removes one or more event handlers, added with the delegate() method.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("body").delegate("p","click",function(){
$(this).slideToggle();
});
$("button").click(function(){
$("body").undelegate();
}); });
</script> </head> <body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>Click any p element to make it disappear. Including this one.</p>
<button>Remove event handlers, added with the delegate() method, from all elements</button>
</body> </html>
jQuery Event unload() Method
---------------------------------------
Definition and Usage

The unload event occurs when the user navigates away from the page.

The unload event is triggered when:

a link to leave the page is clicked
a new URL is typed in the address bar
the forward or back buttons are used
the browser window is closed
the page is reloaded
The unload() method specifies what happens when a unload event occurs.

The unload() method should only be used on the window object.
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(window).unload(function(){
alert("Goodbye!");
}); });
</script> </head> <body>
<p>When you click <a href="http://w3schools.com">this link</a>, or close the window, an alert box will be triggered.</p> </body> </html>
get height of window or element
var height = $(document).height();
var img_height = $('img#testimage1').height();
force jquery ro display a variable in console (Firefox, error on IE but still works)
console.log(imageHeight);
multiple css propert set in 1 jQuery statement
$('img#testimage1').css({ "width": 100, "height": 1000});
jQuery Effect animate() Method
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.

$("#btn1").click(function(){
$("#box").animate({height:"300px"});
});
jQuery Effect clearQueue() Method
Stop all functions in the queue that has not yet been executed.

Unlike the stop() method (that only works with animations), the clearQueue() can remove any queued function.

$("#stop").click(function(){
$("#box").clearQueue();
});
start and stop
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#start").click(function(){
$("#box").animate({height:300},"slow");
$("#box").animate({width:300},"slow");
$("#box").queue(function () {
$(this).css("background-color","red");
$(this).dequeue();
});
$("#box").animate({height:100},"slow");
$("#box").animate({width:100},"slow");
});
$("#stop").click(function(){
$("#box").clearQueue();
}); });
</script> </head> <body>
<p><button id="start">Start Animation</button><button id="stop">Stop Animation</button></p>
<div id="box" style="background:#98bf21;height:100px;width:100px;position:relative">
</div> </body> </html>
jQuery Effect fadeIn() Method
fadeIn() method gradually changes the opacity, for selected elements, from hidden to visible (fading effect).

$(".btn2").click(function(){
$("p").fadeIn();
});
jQuery Effect fadeOut() Method
fadeOut() method gradually changes the opacity, for selected elements, from visible to hidden (fading effect).

$(".btn1").click(function(){
$("p").fadeOut();
});
jQuery Effect fadeTo() Method
fadeTo() method gradually changes the opacity, for selected elements, to a specified opacity (fading effect).

$("button").click(function(){
$("p").fadeTo(1000,0.4);
});
jQuery Effect slideDown() Method
slideDown() method gradually changes the height, for selected elements, from hidden to visible (slide effect).

$(".btn2").click(function(){
$("p").slideDown();
});
jQuery Effect slideToggle() Method
slideToggle() method toggles between slideUp() and slideDown() for the selected elements.

This method checks each element for visibility. slideDown() is run if an element is hidden. slideUp() is run if an element is visible - This creates a toggle effect.

$("button").click(function(){
$("p").slideToggle();
});
jQuery Effect slideUp() Method
slideUp() method gradually changes the height, for selected elements, from visible to hidden (slide effect).

$(".btn1").click(function(){
$("p").slideUp();
});
jQuery Effect stop() Method
stop() method stops the currently running animation for selected elements.

$("#stop").click(function(){
$("div").stop();
});
jQuery HTML addClass() Method
addClass() method adds one or more classes to the selected elements.

This method does not remove existing class attributes, it only adds one or more values to the class attribute.

Tip: To add more than one class, separate the class names with space.

$("button").click(function(){
$("p:first").addClass("intro");
});
jQuery HTML after() Method
after() method inserts specified content after the selected elements.

$("button").click(function(){
$("p").after("<p>Hello world!</p>");
});
jQuery HTML append() Method
append() method inserts specified content at the end of (but still inside) the selected elements.

$("button").click(function(){
$("p").append(" <b>Hello world!</b>");
});
jQuery HTML appendTo() Method
appendTo() method inserts specified content at the end of (but still inside) the selected elements.

$("button").click(function(){
$("<b>Hello World!</b>").appendTo("p");
});
jQuery HTML attr() Method
attr() method sets or returns attribute values of selected elements.

This method works differently depending on the parameters.

$("button").click(function(){
$("img").attr("width","150");
});
change the width of an image using attr()
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("img").attr("width","150");
}); });
</script> </head> <body>
<img src="img_pulpitrock.jpg" alt="Pulpit Rock" width="284" height="213" /> <br />
<button>Set the width attribute of the image</button> </body> </html>
jQuery HTML before() Method
before() method inserts specified content in front of (before) the selected elements.

$("button").click(function(){
$("p").before("<p>Hello world!</p>");
});
jQuery HTML clone() Method
clone() method makes a copy of selected elements, including child nodes, text and attributes.

$("button").click(function(){
$("p").clone().appendTo("body");
});
jQuery HTML detach() Method
detach() method removes the selected elements, including all text and child nodes.

This method keeps a copy of the removed elements, which allows them to be reinserted at a later time.

The detach() method also keeps the element's jQuery data, like event handlers.

$("button").click(function(){
$("p").detach();
});
jQuery HTML empty() Method
empty() method removes all content from selected elements, including text and child nodes.

$("button").click(function(){
$("p").empty();
});
jQuery HTML hasClass() Method
hasClass() method checks if any of the selected elements have a specified class.

If ANY of the selected elements has the specified class, this method will return "true".

$("button").click(function(){
alert($("p").hasClass("intro"));
});
jQuery HTML html() Method
html() method sets or returns the content (innerHTML) of the selected elements.

$("button").click(function(){
$("p").html("Hello <b>world</b>!");
});
jQuery HTML insertAfter() Method
insertAfter() method inserts HTML markup or existing elements after the selected elements.

$("button").click(function(){
$("<span>Hello world!</span>").insertAfter("p");
});
jQuery HTML insertBefore() Method
insertBefore() method inserts HTML markup or existing elements before the selected elements.

$("button").click(function(){
$("<span>Hello world!</span>").insertBefore("p");
});
jQuery HTML prepend() Method and prepentTo()
prepend() method inserts specified content at the beginning of (but still inside) the selected elements.

$("button").click(function(){
$("p").prepend(" <b>Hello world!</b>");
});
jQuery HTML remove() Method
remove() method removes the selected elements, including all text and child nodes.

$("button").click(function(){
$("p").remove();
});
jQuery HTML removeAttr() Method
removeAttr() method removes a specified attribute from the selected elements.

$("button").click(function(){
$("p").removeAttr("style");
});
jQuery HTML removeClass() Method
removeClass() method removes one or more classes from the selected elements.

$("button").click(function(){
$("p").removeClass("intro");
});
jQuery HTML replaceAll() Method
replaceAll() method replaces selected elements with new content.

$("button").click(function(){
$("<b>Hello world!</b>").replaceAll("p");
});
jQuery HTML replaceWith() Method
replaceWith() method replaces selected elements with new content.

$("button").click(function(){
$("p:first").replaceWith("<b>Hello world!</b>");
});
jQuery HTML text() Method
text() method sets or returns the text content of the selected elements.

$("button").click(function(){
$("p").text("Hello world!");
});
jQuery HTML unwrap() Method
unwrap() method removes the parent element of the selected elements.

$("button").click(function(){
$("p").unwrap();
});
jQuery HTML val() Method
method returns or sets the value attribute of the selected elements.

$("button").click(function(){
$("input:text").val("Glenn Quagmire");
});
jQuery HTML wrap() Method
wrap() method wraps specified HTML element(s) around each selected element.

$("button").click(function(){
$("p").wrap("<div></div>");
});
jQuery HTML wrapAll() Method
wrapAll() method wraps specified HTML element(s) around all selected elements.

<html> <head> <style>
div { border: 2px solid blue; }
p { background:yellow; margin:4px; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head> <body>
<p>Hello</p> <p>cruel</p> <p>World</p>
<script>$("p").wrapAll("<div></div>");</script>
</body> </html>
jQuery HTML wrapInner() Method
wrapInner() method wraps specified HTML element(s) around the content (innerHTML) of each selected element.
-----------------------------------------------------------------------
<!DOCTYPE html> <html> <head>
<style>p { background:#bbf; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head> <body>
<p>Hello</p> <p>cruel</p> <p>World</p>
<script>$("p").wrapInner("<i></i>");</script>
</body> </html>
jQuery CSS addClass() Method
addClass() method adds one or more classes to the selected elements.

This method does not remove existing class attributes, it only adds one or more values to the class attribute.

Tip: To add more than one class, separate the class names with space.

$("button").click(function(){
$("p:first").addClass("intro");
});
jQuery CSS css() Method
css() method sets or returns one or more style properties for the selected elements.

$("button").click(function(){
$("p").css("color","red");
});
jQuery CSS hasClass() Method
hasClass() method checks if any of the selected elements have a specified class.

If ANY of the selected elements has the specified class, this method will return "true".

$("button").click(function(){
alert($("p").hasClass("intro"));
});
jQuery CSS offset() Method
offset() method set or returns the offset (position) for the selected elements, relative to the document.

$("button").click(function(){
x=$("p").offset();
alert("Left offset: " + x.left + " Top offset: " + x.top);
});
jQuery CSS offsetParent() Method
offsetParent() method returns the closest ancestor (parent) element with a specified position (a position different than default).

$("button").click(function(){
$("p").offsetParent().css("background-color","red");
});
jQuery CSS position() Method
position() method returns the position of the first selected element, relative to the parent element.

This method returns an object with 2 properties, top and left, which represent the top and left positions in pixels.

$("button").click(function(){
x=$("p").position();
alert("Left position: " + x.left + " Top position: " + x.top);
});
jQuery CSS removeClass() Method
removeClass() method removes one or more classes from the selected elements.

$("button").click(function(){
$("p").removeClass("intro");
});
jQuery CSS scrollLeft() Method
scrollLeft() method sets or returns the horizontal position of the scrollbar for the selected elements.

The horizontal position of the scrollbar is the number of pixels scrolled from its left side. When the scrollbar is on the far left side, the position is 0.

$("button").click(function(){
alert($("div").scrollLeft()+" px");
});
jQuery CSS scrollTop() Method
scrollTop() method sets or returns the vertical position of the scrollbar for the selected elements.

The vertical position of the scrollbar is the number of pixels scrolled from the top. When the scrollbar is on the top, the position is 0.

$("button").click(function(){
alert($("div").scrollTop()+" px");
});
jQuery CSS toggleClass() Method
toggleClass() method toggles between adding and removing one or more classes for the selected elements.

This method checks each element for the specified classes. The classes are added if missing, and removed if already set - This creates a toggle effect.

However, by using the "switch" parameter, you can specify to only remove, or only add a class.

$("button").click(function(){
$("p").toggleClass("main");
});
jQuery AJAX ajax() Method
ajax() method is used to perform an AJAX (asynchronous HTTP) request.

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

All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.
jQuery AJAX ajaxComplete() Method
ajaxComplete() method specifies a function to be run when an AJAX request completes.

Unlike ajaxSuccess(), functions specified with the ajaxComplete() method will run when the request is completed, even it is not successful.

$("#txt").ajaxStart(function(){
$("#wait").css("display","block");
});
$("#txt").ajaxComplete(function(){
$("#wait").css("display","none");
});
jQuery AJAX ajaxError() Method
ajaxError() method specifies a function to be run when an AJAX request fails.

$("div").ajaxError(function(){
alert("An error occurred!");
});
jQuery AJAX ajaxSend() Method
ajaxSend() method specifies a function to run when an AJAX requests is about to be sent.

$("div").ajaxSend(function(e,xhr,opt){
$(this).html("Requesting " + opt.url);
});
jQuery AJAX ajaxSetup() Method
Set the default URL and success function for all AJAX requests:
--------------------------------------------

<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajaxSetup({url:"demo_ajax_load.txt",success:function(result){
$("div").html(result);}});
$.ajax(); }); });
</script> </head> <body>
<div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button> </body> </html>
jQuery AJAX ajaxStart() Method
ajaxStart() method specifies a function to be run when an AJAX request starts.
------------------------------------
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div").ajaxStart(function(){
$(this).html("<img src='demo_wait.gif' />");
});
$("button").click(function(){
$("div").load("demo_ajax_load.asp");
}); }); </script> </head> <body>
<div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button> </body> </html>
jQuery AJAX ajaxStop() Method
The ajaxStop() method specifies a function to run when ALL AJAX requests have completed.

When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.
---------------------------------------
$("div").ajaxStop(function(){
alert("All AJAX requests completed");
});
jQuery AJAX ajaxSuccess() Method
The ajaxSuccess() method specifies a function to be run when an AJAX request is successfully completed.
-----------------------------------
$("div").ajaxSuccess(function(){
alert("AJAX request successfully completed");
});
jQuery AJAX get() Method
The get() method is used to perform an AJAX HTTP GET request.
--------------------------------------------
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
  $.get("demo_ajax_load.txt", function(result){
    $("div").html(result);
  }); }); });
</script> </head> <body>
<div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button> </body> </html>
jQuery AJAX getJSON() Method
The getJSON() method is used to get JSON data using an AJAX HTTP GET request.
--------------------------------------------

<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
}); }); });});
</script> </head> <body>
<button>Get JSON data</button>
<div></div> </body> </html>
jQuery AJAX getScript() Method
The getScript() method is used to get and execute a JavaScript using an AJAX HTTP GET request.
------------------------------------------

<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.getScript("demo_ajax_script.js"); }); });
</script> </head> <body>
<button>Use Ajax to get and then run a JavaScript</button>
</body> </html>
jQuery AJAX load() Method
The load() method loads data from a server using an AJAX request, and places the returned data into the specified element.
------------------------------------------

<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("div").load('demo_ajax_load.txt');
}); });
</script> </head> <body>
<div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button> </body> </html>
jQuery AJAX param() Method
The param() method creates a serialized representation of an array or an object.
The serialized values can be used in the URL query string when making an AJAX request.
------------------------------------------
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";
$("button").click(function(){
$("div").text($.param(personObj)); }); });
</script> </head> <body>
<button>Serialize object</button> <div></div>
</body> </html>
jQuery AJAX post() Method
The post() method is used to perform an AJAX HTTP POST request.
--------------------------------------------
$("input").keyup(function(){
txt=$("input").val();
$.post("demo_ajax_gethint.asp",{suggest:txt},function(result){
$("span").html(result);
}); });
jQuery AJAX serialize() Method
The serialize() method creates a URL 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.
----------------------------------------

<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("div").text($("form").serialize()); }); });
</script> </head> <body>
<form action="">
First name: <input type="text" name="FirstName" value="Mickey" /><br />
Last name: <input type="text" name="LastName" value="Mouse" /><br /> </form>
<button>Serialize form values</button>
<div></div> </body> </html>
jQuery AJAX serializeArray() Method
The serializeArray() method creates an array 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.
------------------------------------------

<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
x=$("form").serializeArray();
$.each(x, function(i, field){
$("#results").append(field.name + ":" + field.value + " "); });});});
</script> </head><body>
<form action="">
First name: <input type="text" name="FirstName" value="Mickey" /><br />
Last name: <input type="text" name="LastName" value="Mouse" /><br /> </form>
<button>Serialize form values</button>
<div id="results"></div> </body> </html>
jQuery Misc data() Method
The data() method attaches data to, or gets data from, selected elements.
-------------------------------
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn1").click(function(){
$("div").data("greeting", "Hello World");
});
$("#btn2").click(function(){
alert($("div").data("greeting")); }); });
</script> </head> <body>
<button id="btn1">Attach data to div element</button><br />
<button id="btn2">Get data attached to div element</button>
<div></div> </body> </html>
jQuery Misc each() Method
The each() method specifies a function to run for each matched element.
---------------------------------------------

<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("li").each(function(){
alert($(this).text()) }); });});
</script> </head> <body>
<button>Alert the value of each list item</button>
<ul> <li>Coffee</li> <li>Milk</li> <li>Soda</li> </ul>
</body> </html>
jQuery Misc index() Method
The index() method returns the index position of specified elements relative to other specified elements.
The elements can be specified by jQuery selectors, or a DOM element.
--------------------------------------------
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("li").click(function(){
alert($(this).index()); });});
</script> </head> <body>
<p>Click the list items to get the index position, relative to its sibling elements</p>
<ul> <li>Coffee</li> <li>Milk</li> <li>Soda</li> </ul>
</body> </html>
jQuery Misc noConflict() Method
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.
------------------------------------

<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var jq=$.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>
jQuery Misc removeData() Method
The removeData() method removes data previously set with the data() method.
-----------------------------------------
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn1").click(function(){
$("div").data("greeting", "Hello World");
alert("Greeting is: " + $("div").data("greeting"));
});
$("#btn2").click(function(){
$("div").removeData("greeting");
alert("Greeting is: " + $("div").data("greeting"));
}); }); </script> </head> <body>
<button id="btn1">Attach data to div element</button><br />
<button id="btn2">Remove data attached to div element</button>
<div></div> </body> </html>
jQuery Misc size() Method
The size() method returns the number of elements matched by the jQuery selector.
------------------------------------------
<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
alert($("li").size()); });});
</script></head><body>
<button>Alert the number of li elements</button>
<ul><li>Coffee</li><li>Milk</li><li>Soda</li></ul>
</body></html>
jQuery Misc toArray() Method
The toArray() method returns the elements matched by the jQuery selector as an array.
------------------------------------------

<html> <head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
x=$("li").toArray()
for (i=0;i<x.length;i++) { alert(x[i].innerHTML); } }); });
</script> </head> <body>
<button>Alert the value of each list item</button>
<ul> <li>Coffee</li> <li>Milk</li> <li>Soda</li> </ul>
</body> </html>
wrapInner + document.createElement example for wrapping bold tag around each of the p tags
<!DOCTYPE html><html> <head>
<style>p { background:#9f9; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body> <p>Hello</p><p>cruel</p> <p>World</p>
<script>$("p").wrapInner(document.createElement("b"));</script> </body> </html>
.wrapAll() function
can take any string or object that could be passed to the $() function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. The structure will be wrapped around all of the elements in the set of matched elements, as a single group.
jQuery.when( deferreds )
Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.
Example: Execute a function after two ajax requests are successful.
Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error. (examples for .when() and .ajax())
$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
.then(myFunc, myFailure);
Execute a function after two ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request). (examples for .when() and .ajax())
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
/* a1 and a2 are arguments resolved for the
page1 and page2 ajax requests, respectively */
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
if ( /Whip It/.test(jqXHR.responseText) ) {
alert("First page has 'Whip It' somewhere.");
}
});
jQuery.unique()
The $.unique() function searches through an array of objects, sorting the array, and removing any duplicate nodes. This function only works on plain JavaScript arrays of DOM elements, and is chiefly used internally by jQuery.

As of jQuery 1.4 the results will always be returned in document order.
jQuery.type()
Determine the internal JavaScript [[Class]] of an object.
Determine if object is a boolean
jQuery.type(true) === "boolean"
Determine if object is a number
jQuery.type(3) === "number"
Determine if object is a string
jQuery.type("test") === "string"
Determine if object is a a function
jQuery.type(function(){}) === "function"
Determine if object is an array
jQuery.type([]) === "array"
Determine if object is a date
jQuery.type(new Date()) === "date"
Determine if object is a regexp
jQuery.type(/test/) === "regexp"
jQuery.trim()
The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved.
--------------------------------------------
<script>
var str = " lots of spaces before and after ";
$("#original").html("Original String: '" + str + "'");
$("#trimmed").html("$.trim()'ed: '" + $.trim(str) + "'");
</script>
-------------------------------------------
Original String: ' lots of spaces before and after '
$.trim()'ed: 'lots of spaces before and after'
toggleClass() example for highlightin
<html> <head> <style>
p { margin: 4px; font-size:16px; font-weight:bolder;
cursor:pointer; }
.highlight { background:yellow; } </style>
<script src="http://code.jquery.com/jquery-latest.js"></script></head>
<body>
<p class="blue">Click to toggle</p>
<p class="blue">highlight</p>
<p class="blue">on these</p>
<p class="blue">paragraphs</p>
<script>
$("p").click(function () {
$(this).toggleClass("highlight"); });
</script> </body> </html>
:text Selector
Selects all elements of type text.
-----------------------------------
var input = $("form input:text").css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
.text() Get the combined text contents of each element in the set of matched elements, including their descendants.
<html> <head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head> <body>
<p><b>Test</b> Paragraph.</p>
<p></p>
<script>
var str = $("p:first").text();
$("p:last").html(str);
</script> </body> </html>
jQuery.support
A collection of properties that represent the presence of different browser features or bugs. Primarily intended for jQuery's internal use; specific properties may be removed when they are no longer needed internally to improve page startup performance.
jQuery.sub()
Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object.
select all td tags in jQuery
$("td")
all <h3> tags preceeded by <p> tag syntax
$("p + h3")
select every element in a div called superhuman
$("#superhuman > *").css("color", "red");
select a sbling of an item with of superhuma
$("#superhuman ~ h4").css("color", "red");
select any div that has an h4 tag
$("div:has(h4)").css("color", "red");
select any div that has an associated id propertty
$("div[id]").css("color", "red");
select any item that has a particular class defined
$("li[class='hero']").css("color", "red");
select an <li> element that contains a particular text inside of it
$("li:contains('Richard')").css("color", "red");
hover table
<script type="text/javascript">
$(document).ready(function(){
$("#numbers tr:odd").addClass("nice");
$("#numbers tr").mouseover(function() { $(this).addClass("mouseon"); });
$("#numbers tr").mouseout(function() { $(this).removeClass("mouseon"); });
$("#numbers tr").click(function() { $(this).addClass("mouseon"); }); });
</script>
add css class to odd rows that highlights them
css class ---
tr.nice td {
background: #FAFAD2;
}
jquery code-----
$("#numbers tr:odd").addClass("nice");
click toggle the function between multiple
$("tr").toggle(
function () { $(this).css({"color":"blue"}); },
function () { $(this).css({"color":"red"}); },
function () { $(this).css({"color":""}); }
);
use addclass to change an element
----- css -------
tr.mouseon td {
background: red;
}
----- jQuery -----
$("tr").toggle(
function () { $(this).addClass("mouseon"); },
function () { $(this).removeClass("mouseon"); } );
check if a property is set for an element and usage of an if statemenet in jQuery
$('#bringbacl').click(function ()
{
if($('#clickToHide').is(':visible')) {
$('#clickToHide').hide();
} else {
$('#clickToHiode').show();
}
})
set the value of an element
$('#bringitback').click( function() {
$(this).val('Delete Text');
});
bind in jQuery, allows you to bind multiple events
'$("document").ready(function() {
$('oneButton').bind('click;, alertButtonClick);
});

function alertButtonClick() {
alert("There was button click");
}
get window width or height
function resizeWindow()
{
$("#second").html("Windows was resize w: " + $(window).width() + " H: " $(window).height());
}
}
change text on tag after clicking on it pure jQuery
----html----
<h2 id="test">Test</h2>
---jQuery-----
$('#test').click(function() {
$(this).text('www.something.com'); });
change text on tag after clicking on it by binding an function to it
<form action="">
<button type="button" id="replaceWHtml">Replace with HTML</button>
</form>
----jQuery---
$("document").ready(function(){ $('#replaceWHtml').bind('click', replaceWHtml);};
--- JS ----
function replaceWHtml() {
$('#h3Tag').html('<h6>Now I\'m an h6 tag</h6>'); }
For click and most other events, you can prevent the default behaviour - here, following the link to jquery.com - by calling event.preventDefault() in the event handler:
$(document).ready(function(){
$("a").click(function(event){
alert("As you can see, the link no longer took you to jquery.com");
event.preventDefault();
});
});
how to benefit from google cdn
<script type="text/javascript" src="http://www.google.com/jsapi"></script><script type="text/javascript">// <![CDATA[
// You may specify partial version numbers, such as "1" or "1.3",
// with the same result. Doing so will automatically load the
// latest version matching that partial revision pattern
// (e.g. 1.3 would load 1.3.2 today and 1 would load 1.8.0).
google.load("jquery", "1.8.0");

google.setOnLoadCallback(function() {
// Place init code here instead of $(document).ready()
});
// ]]></script>
Constrain the movement of each draggable by defining the boundaries of the draggable area Set the axis option to limit the draggable's path to the x- or y-axis, or use the containment option to specify a parent DOM element or a jQuery selector, like 'document.'
<script>
$(function() {
$( "#draggable" ).draggable({ axis: "y" });
$( "#draggable2" ).draggable({ axis: "x" });
$( "#draggable3" ).draggable({ containment: "#containment-wrapper", scroll: false });
$( "#draggable5" ).draggable({ containment: "parent" }); }); </script>
Effects that can be used with Show/Hide/Toggle:
Blind - Blinds the element away or shows it by blinding it in.
Clip - Clips the element on or off, vertically or horizontally.
Drop - Drops the element away or shows it by dropping it in.
Explode - Explodes the element into multiple pieces.
Fade - Fades the element, by gradually changing its opacity.
Fold - Folds the element like a piece of paper.
Puff - Scale and fade out animations create the puff effect.
Slide - Slides the element out of the viewport.
Scale - Shrink or grow an element by a percentage factor.
Inside the ready event, add a click handler to the link:
$(document).ready(function(){
$("a").click(function(event){
alert("Thanks for visiting!"); }); });
<!-- HTML -- >
<a href="http://jquery.com/">Click to visti jQuery</a>
callback function
callback is a function that is passed as an argument to another function and is executed after its parent function has completed. The special thing about a callback is that functions that appear after the "parent" can execute before the callback executes. Another important thing to know is how to properly pass the callback
Callback with no arguments you pass it like this:

Callback with arguments:
$.get('myhtmlpage.html', myCallBack);

$.get('myhtmlpage.html', function(){
myCallBack('foo', 'bar'); });

myCallBack is invoked when the '$.get' is done getting the page. each()
each()
iterates over every element and allows further processing

$(document).ready(function() {
$("#orderedlist").find("li").each(function(i) {
$(this).append( " BAM! " + i ); }); });
get the number of paragraphs in an div element
alert($("div.contentToChange p").size());
implicit iteration
methods are designed to automatically work on sets of objects instead of individual ones

like .hide()
chaining in jQuery
jQuery employs a programming pattern called chaining for the majority of its methods. This means that the result of most operations on an object is the object itself, ready for the next action to be applied to it.
Selects all elements
Selects the current HTML element
Selects all elements - $("*")
Selects the current HTML element - $(this)
Selects all <p> elements with class="intro"
Selects the first <p> element
Selects the first <li> element of the first <ul>
Selects all <p> elements with class="intro" - $("p.intro")
Selects the first <p> element - $("p:first")
Selects the first <li> element of the first <ul> - $("ul li:first")
Selects the first <li> element of every <ul>
Selects all elements with an href attribute
Selects the first <li> element of every <ul> - $("ul li:first-child")
Selects all elements with an href attribute - $("[href]")
Selects all <a> elements with a target attribute value equal to "_blank"
Selects all <a> elements with a target attribute value NOT equal to "_blank"
Selects all <a> elements with a target attribute value equal to "_blank" - $("a[target='_blank']")
Selects all <a> elements with a target attribute value NOT equal to "_blank" - $("a[target!='_blank']")
Selects all <button> elements and <input> elements of type="button
Selects all even <tr> elements
Selects all odd <tr> elements
Selects all <button> elements and <input> elements of type="button - $(":button")
Selects all even <tr> elements - $("tr:even")
Selects all odd <tr> elements - $("tr:odd")
jQuery animate() - Using Relative Values
$("button").click(function(){
$("div").animate({
left:'250px',
height:'+=150px',
width:'+=150px' }); });
jQuery animate() - Uses Queue Functionality
$("button").click(function(){
var div=$("div");
div.animate({height:'300px',opacity:'0.4'},"slow");
div.animate({width:'300px',opacity:'0.8'},"slow");
div.animate({height:'100px',opacity:'0.4'},"slow");
div.animate({width:'100px',opacity:'0.8'},"slow"); });
jQuery Dimension Methods
jQuery has several important methods for working with dimensions:

width()
height()
innerWidth()
innerHeight()
outerWidth()
outerHeight()
width() method sets or returns the width of ?

height() method ?
width() method sets or returns the width of an element (includes NO padding, border, or margin).

height() method sets or returns the height of an element (includes NO padding, border, or margin).
innerWidth() and innerHeight() Methods
The innerWidth() method returns the width of an element (includes padding).

The innerHeight() method returns the height of an element (includes padding).
jQuery outerWidth() and outerHeight() Methods
--------------------------------------------------------------------------------
jQuery outerWidth() and outerHeight() Methods

The outerWidth() method returns the width of an element (includes padding and border).

The outerHeight() method returns the height of an element (includes padding and border).
following example returns the width and height of the document (the HTML document) and window (the browser viewport):
$(document).ready(function(){
$("button").click(function(){
var txt="";
txt+="Document width/height: " + $(document).width();
txt+="x" + $(document).height() + "\n";
txt+="Window width/height: " + $(window).width();
txt+="x" + $(window).height();
alert(txt);
}); });
implicit iteration in jQuery (def)
methods are designed to automatically work on sets of objects instead of individual ones

Find all elements with the class collapsible and hide them
chaining in jQuery (def)
a programming pattern called chaining
It means that the result of most operation on an object is the object itself, ready for the next action to be applied to it.
factory function

child combinator
$()
$ is an alias for jQuery

child combinator (>)
$(document).ready(function() {
$('#selected-plays > li').addClass('horizontal');
});

find each list item (li) that is a child (>) of the element with an ID of selected-plays
negation pseudo-class sample
$('#selected-plays li:not(.horizontal)').addClass('sub-level');

This time we are selecting every list item (li) that:
1. Is a descendant of the element with an ID of selected-plays (#selected-plays)
2. Does not have a class of horizontal (:not(.horizontal))
add a hyperlink class for all links with an href value that both starts with http and contains henry anywhere:
$('a[href^=http][href*=henry]') .addClass('henrylink');
:odd and :even selectors and multiple tables
when we have multiple tables on a page if the last row of a table is tagged by odd then the first row of the second table will not be tagged by odd to avoid this use :nth-child(odd) vs just :odd
:contains() selector
suppose for some reason we want to highlight any table cell that contains Henry

$('td:contains(Henry)').addClass('highlight');

:contains() selector is case sensitive
select all checked radio buttons (but not checkboxes)

select all password inputs and disabled text inputs with
$(':radio:checked')

$(':password, :text:disabled')
how to write a complex test for whether a link is external and add a class to those (.filter() / code)
.filter() method takes a function as an argument
Without a filter function, we'd be forced to explicitly loop through each element, testing each one separately. But with the following filter function

$('a').filter(function() {
return this.hostname && this.hostname != location.hostname;
}).addClass('external');

.filter() method iterates through the matched set of elements, testing the return value of the function against each one. If the function returns false, the element is removed from the matched set. If it returns true, the element is kept
next() method
example style the cell next to each cell containing Henry
.next() method selects only the very next sibling element

$(document).ready(function() {
$('td:contains(Henry)').next().addClass('highlight');
});

.nextAll() selects all sibling following

There is also prev()/prevAll()
Animate the first paragraph tag so that when clicked, it grows and shrinks. Use linear easing as it grows, and swing easing as it shrinks
$('p:first').toggle(function() {
$(this).animate({'height':'+=150px'}, 2000, 'linear;);
}, function () {
$(this).animate({'height':'-=150px'}, 2000, 'swing');
});
.filter()
<ul> <li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li> </ul>
$('li').filter(':even').css('background-color', 'red');

The result of this call is a red background for items 1, 3, and 5, as they match the selector (recall that :even and :odd use 0-based indexing).
callback func. (expl and code)
Many effects accept a special parameter known as a callback.
Callbacks specify code that needs to run after the effect has finished.

$('#disclaimer').slideToggle('slow', function() {
alert('The slide has finished sliding!')
});
How you tell JQ that when our documents is ready run our function
$(document).ready(function() {
alert('Welcome to StarkEnterprise!');
});
reading CSS properties
$(document).ready(function () {
var fontSize = $('#celebs tbody tr:first').css('font-size');
alert(fontSize);
});
We have following button
<input type="button" id="toggleButton" value="toggle" />
When this is clicked we check to find out if we show or hide the disclaimer
$('#toggleButton').click( function() {
if ($('#disclaimer')is('visible')) {
$('disclaimer').hide();
} else {
$('disclaimer').show();
}
});
How to create a full HTML element from JQ
$('<div>', {
id: 'specialButton',
text: 'Click Me!',
click: function() {
alert("Advanced jQuery!")
}).insertBefore("#disclaimer');