The main purpose of these selectors is to select elements on a web page that meet certain criteria. The criteria can be anything like their id, classname, attributes or a combination of any or all of these. Most of the selectors in jQuery are based on existing CSS selectors but the library also has its own custom selectors.

1. Commonly Used jQuery Selectors:

            //--- COMMON JQUERY SELECTORS ---//
            // get element by id
            $("#ElementID").whatever();

            // get element by css class
            $(".ClassName").whatever();

            // get elements where id contains a string
            $("[id*='value']").whatever();

            // get elements where id starts with a string
            $("[id^='value']").whatever();

            // get elements where id ends with a string
            $("[id$='value']").whatever();

            // get all elements of certain type (can use "p", "a", "div" - any html tag)
            $("div").whatever();
 

2. jQuery Toggle, Show and Hide Functions:

            //--- JQUERY TOGGLE/SHOW/HIDE ---//
            // toggle hide/show of an element
            $("#DivID").toggle(1000);

            // do something when animation is complete
            $("#DivID").toggle(1000, function () {
                alert("Toggle Complete");
            });


            // hide an element
            $("#DivID").hide(1000);

            // do something when animation is complete
            $("#DivID").hide(1000, function () {
                alert("Hide Complete");
            });


            // show an element
            $("#DivID").show(1000);

            // do something when animation is complete
            $("#DivID").show(1000, function () {
                alert("Show Complete");
            });
 

3. jQuery Slide Functions:

            //--- JQUERY SLIDE - SLIDE AN ELEMENT IN AND OUT ---//
            // toggle slide up and down
            $("#DivID").slideToggle(1000);

            // do something when animation complete
            $("#DivID").slideToggle(1000, function () {
                alert("Slide Toggle Complete");
            });

            // slide up
            $("#DivID").slideUp(1000);

            // do something when animation is complete
            $("#DivID").slideUp(1000, function () {
                alert("Slide Up Complete");
            });

            // slide down
            $("#DivID").slideDown(1000);

            // do something when animation is complete
            $("#DivID").slideDown(1000, function () {
                alert("Slide Down Complete");
            });
 

4. jQuery Fade Functions:

            //--- JQUERY FADE - FADE AN ELEMENT IN, OUT & TO ---//
            // fade in
            $("#DivID").fadeIn(1000);

            // do something when animation complete
            $("#DivID").fadeIn(1000, function () {
                alert("Fade In Complete");
            });

            // fade out
            $("#DivID").fadeOut(1000);

            // do something when animation is complete
            $("#DivID").fadeOut(1000, function () {
                alert("Fade Out Complete");
            });

            // fade to (fades to specified opacity)
            $("#DivID").fadeTo(1000, 0.25);

            // do something when animation is complete
            $("#DivID").fadeTo(1000, 0.25, function () {
                alert("Fade To Complete");
            });
 

5. jQuery Animate Functions:

            //--- ANIMATE (EXAMPLE USES OPACITY, BUT CAN USE ANY CSS PROPERTY. ---//
            //--- NOTE SOME MY REQUIRE THE USE OF A PLUGIN SUCH AS JQUERY COLOR ANIMATION PLUGIN. ---//
            $("#DivID").animate({ opacity: 0.25 }, 1000);

            // do something when animation complete
            $("#DivID").animate({ opacity: 0.25 }, 1000, function () {
                alert("Opacity Animation Complete");
            });
 

6. Add & Remove CSS Classes:

            //--- ADD & REMOVE CSS CLASSES ---///
            // add css class
            $("#DivID").addClass("newclassname");

            // remove css class
            $("#DivID").removeClass("classname");

            // add & remove class together
            $("#DivID").removeClass("classname").addClass("newclassname");

            // add & remove multiple classes
            $("#DivID").removeClass("classname classname2").addClass("newclassname newclassname2");
 

7. Get & Set Textbox Values: 

            //--- GET & SET TEXTBOX VALUE ---// 
            //--- CAN ALSO BE USED ON ANY OTHER ELEMENT THAT HAS A VALUE PROPERTY ---//
            // get the value of a textbox
            var TextboxValue = $("#TextboxID").val();

            // set the value of a textbox
            $("#TextboxID").val("New Textbox Value Here");
 

8. Get & Set Element's HTML:

            //--- GET & SET HTML OF ELEMENT ---//
            // get element html
            var DivHTML = $("#DivID").html();

            // set element html
            $("#DivID").html("<p>This is the new html</p>");
 

9. Get & Set Element's Text:

            //--- GET & SET TEXT OF ELEMENT ---//
            // get text of element
            var DivText = $("#DivID").text();

            // set text of element
            $("#DivID").text("This is the new text.");
 

10. Get & Set Element's Width & Height:

            //--- GET & SET ELEMENT'S WIDTH & HEIGHT
            // get element height
            var ElementHeight = $("#DivID").height();

            // set element height
            $("#DivID").height(300);


            // get element width
            var ElementWidth = $("#DivID").width();

            // set element width
            $("#DivID").width(600);
 

11. EXTRA: Change Element's CSS Property

            //--- CHANGE AN ELEMENT'S CSS PROPERTY ---//
            $("#DivID").css("background-color", "#000");
            $("#DivID").css("border", "solid 2px #ff0000");
 

Determine Browser
Suppose you were to determine the browser type of the browser currently in use. You can use the following piece of code to do this:

$(document).ready(function() {
// If the browser type if Mozilla Firefox
if ($.browser.mozilla && $.browser.version >= "1.8" ){ 
// some code
}
// If the browser type is Opera
if( $.browser.opera)
{
// some code
}
// If the web browser type is Safari
if( $.browser.safari )
{
// some code
}
// If the web browser type is Chrome
if( $.browser.chrome)
{
// some code
}
// If the web browser type is Internet Explorer
if ($.browser.msie && $.browser.version <= 6 )
{
// some code
}
//If the web browser type is Internet Explorer 6 and above
if ($.browser.msie && $.browser.version > 6)
{
// some code
}
});
Detect Current Mouse Coordinates
Now, suppose you need to detect the current mouse coordinates in the web browser in use. To do this, you can write the following piece of code:

$(document).ready(function() {
$().mousemove(function(e)
{
$('# MouseCoordinates ').html("X Axis Position = " + e.pageX + " and Y Axis Position = " + e.pageY);
});
<DIV id=MouseCoordinates></DIV>
});
Check if an Element Exists
To check whether an element exists, you can write the following code:

if ($("#someElement").length)
{ 
//The DOM element exists
}
else
{
//The DOM element doesn't exist
}
Check if an Element Is Visible
To check whether an element is visible, you can use the following piece of code:

if($(element).is(":visible") == "true")
{ 
//The DOM element is visible
}
else
{
//The DOM element is invisible
}
Set a Timer
The following piece of code can be used to set a timer using jQuery:

$(document).ready(function()
{
window.setTimeout(function()
{
// some code
}, 500);
});
jQuery's Chaining Feature
Chaining is a great feature in jQuery that allows you to chain method calls. Here is an example:

$('sampleElement').removeClass('classToBeRemoved').addClass('classToBeAdded');
You can also use jQuery to store state information of DOM elements in your web page. It contains the data() method that you can use to store state information of the DOM elements in key/value pairs. Here is an example:

$('#someElement').data('currentState', 'off');
Lazy Loading
Lazy loading is a great feature in jQuery that ebales you to load only the content that is needed. To use this, you should incorporate the jquery.lazyload.js script file as shown below:

<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.dimensions.js" type="text/javascript"></script>
<script src="jquery.lazyload.js" type="text/javascript"></script>
Next, you can use the lazyload() method as shown below:
$("imageObject").lazyload();
Preloading Images
Preloading images in a web page improves performance. This can particularly be useful while an animation is in progress- your web page need not wait for the image to be loaded. You can use jQuery to preload images with simple code. Here is an example:

jQuery.preloadImagesInWebPage = function() {
for(var ctr = 0; ctr<arguments.length; ctr++)
{
jQuery("<img>").attr("src", arguments[ctr]);
}
}
To use the above method, you can use the following piece of code:
$.preloadImages("image1.gif", "image2.gif", "image3.gif");
To check whether an image has been loaded, you can use the following piece of code:
$('#imageObject').attr('src', 'image1.gif').load(function() {
alert('The image has been loaded…');
});
jQuery Cloning
jQuery supports cloning - you can use the clone() method to create a clone of any DOM element in your web page. Here is an example:

var cloneObject = $('#divObject').clone();

The $(document).ready function is called during page render, i.e., while the objects are still being downloaded in the web browser. To reduce CPU utilization while a page is being loaded, you can bind your jQuery functions in the $(window).load event. Note that this event is fired after all objects have been downloaded successfully. This would improve the application performance to a considerable extent as the page load time would be minimized. Other common ways to improve jQuery performance are by compressing the scripts and limiting DOM manipulation as much as possible.

Consider the following piece of code that appends a DOM element inside a loop:

for (var ctr=0; ctr<=rows.length; ctr++)
{
$('#tableObject').append('<tr><td>'+rows[ctr]+'</td></tr>');
}
The above code can be replaced by a more efficient piece of code to minimize DOM manipulation and hence improve application performance as shown below:
var str = '';
for (var x=0; x<=rows.length; x++)
{
str += '<tr><td>'+rows[x]+'</td></tr>';
}
$('#tableObject').append(str);
References
Here's a list of links to some useful references on jQuery:

jQuery Documentation
20 Tips and Tricks for jQuery Programmers
Improve Your jQuery
10 Ways to Increase Your jQuery Performance
jquery-tips-tricksFollowing are few very useful jQuery Tips and Tricks for all jQuery developers. I am sharing these as I think they will be very useful to you.
Disclaimer: I have not written all of the below code but have collected from various sources from Internet.

1. Optimize performance of complex selectors
Query a subset of the DOM when using complex selectors drastically improves performance:

var subset = $("");
$("input[value^='']", subset);
2. Set Context and improve the performance
On the core jQuery function, specify the context parameter when. Specifying the context parameter allows jQuery to start from a deeper branch in the DOM, rather than from the DOM root. Given a large enough DOM, specifying the context parameter should translate to performance gains.

$("input:radio", document.forms[0]);
3. Live Event Handlers
Set an event handler for any element that matches a selector, even if it gets added to the DOM after the initial page load:

$('button.someClass').live('click', someFunction);
This allows you to load content via ajax, or add them via javascript and have the event handlers get set up properly for those elements automatically.

Likewise, to stop the live event handling:

$('button.someClass').die('click', someFunction);
These live event handlers have a few limitations compared to regular events, but they work great for the majority of cases. Live event will work starting from jQuery 1.3

4. Checking the Index
jQuery has .index but it is a pain to use as you need the list of elements and pass in the element you want the index of

var index = e.g $('#ul>li').index( liDomObject );
The following is easier:

if you want to know the index of an element within a set, e.g. list items within a unordered list:

$("ul > li").click(function ()
{
    var index = $(this).prevAll().length;
});
5. Use jQuery data method
jQuery’s data() method is useful and not well known. It allows you to bind data to DOM elements without modifying the DOM.

6. Fadeout Slideup effect to remove an element
Combine more than one effects in jQuery to animate and remove an element from DOM.

$("#myButton").click(function() {
         $("#myDiv").fadeTo("slow", 0.01, function(){ //fade
             $(this).slideUp("slow", function() { //slide up
                 $(this).remove(); //then remove from the DOM
             });
         });
});
7. Checking if an element exists
Use following snippet to check whether an element exists or not.

if ($("#someDiv").length) {
    //hooray!!! it exists...
}
8. Add dynamically created elements into the DOM
Use following code snippet to create a DIV dynamically and add it into the DOM.
Further Reading: Dynamically Add/Remove rows in HTML table using JavaScript

var newDiv = $('<div></div>');
newDiv.attr("id","myNewDiv").appendTo("body");
9. Line breaks and chainability
Instead of doing:

$("a").hide().addClass().fadeIn().hide();
You can increase readability like so:

$("a")
  .hide()
  .addClass()
  .fadeIn()
  .hide();
10. Creating custom selectors
$.extend($.expr[':'], {
    over100pixels: function(a) {
        return $(a).height() > 100;
    }
});
 
$('.box:over100pixels').click(function() {
    alert('The element you clicked is over 100 pixels high');
});
11. Cloning an object in jQuery
Use .clone() method of jQuery to clone any DOM object in JavaScript.

// Clone the DIV
var cloned = $('#somediv').clone();
jQuery’s clone() method does not clone a JavaScript object. To clone JavaScript object, use following code.

// Shallow copy
var newObject = jQuery.extend({}, oldObject);
 
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
12. Test if something is hidden using jQuery
We use .hide(), .show() methods in jquery to change the visibility of an element. Use following code to check the whether an element is visible or not.

if($(element).is(":visible") == "true") {
       //The element is Visible
}
13. Alternate way of Document Ready
//Instead of
$(document).ready(function() {
    //document ready
});
//Use
$(function(){
    //document ready
});
14. Selecting an element with . (period) in its ID
Use backslash in the selector to select the element having period in its ID.

$("#Address\\.Street").text("Enter this field");
15. Counting immediate child elements
If you want to count all the DIVs present in the element #foo

<div id="foo">
  <div id="bar"></div>
  <div id="baz">
    <div id="biz">
  </div>
  <span><span>
</div>
 
//jQuery code to count child elements
$("#foo > div").size()
16. Make an element to “FLASH”
jQuery.fn.flash = function( color, duration )
{
    var current = this.css( 'color' );
    this.animate( { color: 'rgb(' + color + ')' }, duration / 2 );
    this.animate( { color: current }, duration / 2 );
}
//Then use the above function as:
$( '#importantElement' ).flash( '255,0,0', 1000 );
17. Center an element on the Screen
jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}
 
//Use the above function as:
$(element).center();
18. Getting Parent DIV using closest
If you want to find the wrapping DIV element (regardless of the ID on that DIV) then you’ll want this jQuery selector:

$("#searchBox").closest("div");
19. Disable right-click contextual menu
There’s many Javascript snippets available to disable right-click contextual menu, but JQuery makes things a lot easier:

$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
    });
});
20. Get mouse cursor x and y axis
This script will display the x and y value – the coordinate of the mouse pointer.

$().mousemove(function(e){
    //display the x and y axis values inside the P element
    $('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});
 
<p></p> 
Related Articles
Tutorial: Handle browser events using jQuery JavaScript framework
JQuery Trigger Event on Show/Hide of Element
jQuery Live Event
Delete Row from HTML Table by clicking it using jQuery
jQuery: Get the Text of Element without Child Element
21 JavaScript Tips and Tricks for JavaScript Developers
jQuery :not() selector example
So you've been playing with jQuery for a while now, you're starting to get the hang of it, and you're really liking it! Are you ready to take your jQuery knowledge to level two? Today, I'll demonstrate twenty functions and features you probably haven't seen before!

1 after() / before()
Sometimes you want to insert something into the DOM, but you don't have any good hooks to do it with; append() or prepend() aren't going to cut it and you don't want to add an extra element or id. These two functions might be what you need. They allow you to insert elements into the DOM just before or after another element, so the new element is a sibling of the older one.

1
2
$('#child').after($('<p />')).text('This becomes a sibling of #child'));
$('#child').before($('<p />')).text('Same here, but this is go about #child'));
You can also do this if you're working primarily with the element you want to insert; just use the insertAfter() or insertBefore functions.

1
$('<p>I\'ll be a sibling of #child</p>').insertAfter($('#child'));
2 change()
The change() method is an event handler, just like click() or hover(). The change event is for textareas, text inputs, and select boxes, and it will fire when the value of the target element is changed; note that this is different from the focusOut() or blur() event handlers, which fire when the element loses focus, whether its value has changed or not.

The change() event is perfect for client-side validation; it's much better than blur(), because you won't be re-validating fields if the user doesn't change the value.

1
2
3
4
5
$('input[type=text]').change(function () {
    switch (this.id) {
        /* some validation code here */
    }
});​​​​​​​​​​
3 Context
Context is both a parameter and a property in jQuery. When collecting elements, you can pass in a second parameter to the jQuery function. This parameter, the context, will usually be a DOM element, and it limits the elements returned to item matching your selector that are children of the context element. That might sound a bit confusing, so check out this example:

1
2
3
4
<p class="hello">Hello World</p>
<div id="wrap">
    <p class="hello">Hello World</p>
</div>
01
02
03
04
05
06
07
08
09
10
11
var hi1 = $('.hello'),
    hi2 = $('.hello', $('#wrap').get(0));
 
console.group('hi1');
console.log("Number of elements in collection:", hi1.length);
console.log("Context of the collection:", hi1.context);
console.groupEnd();
console.group('hi2');
console.log("Number of elements in collection:", hi2.length);
console.log("Context of the collection:", hi2.context);
console.groupEnd();
context example
So where would this be useful? One place might be inside an event handler function. If you'd like to get an element within the one the event was fired on, you could pass this as the context:

1
2
3
$('ul#options li').click(function () {
    $('a', this) . . .
});
4 data() / removeData()
Have you ever wanted to store some bit of information about an element? You can do that easily with the data() method. To set a value, you can pass in two parameters (a key and a value) or just one (an object).

1
2
$('#wrap').data('myKey', 'myValue');
$('#container').data({ myOtherKey : 'myOtherValue', year : 2010 });
To get your data back, just call the method with the key of value you want.

1
2
$('#container').data('myOtherKey'); //returns 'myOtherValue'
$('#container').data('year'); //returns 2010
To get all the data that corresponds with an element, call data without any parameters; you'll get an object with all the keys and values you've given to that item.
If you want to delete a key/value pair after you've added it to an element, just call removeData(), passing in the correct key.

1
$('#container').removeData('myOtherKey');
5 queue() / dequeue()
The queue() and dequeue() functions deal with animations. A queue is list of animations to be executed on an element; be default, an element's queue is named 'fx.' Let's set up a scenario:

HTML

1
2
3
4
5
6
<ul>
  <li id="start">Start Animating</li>
  <li id="reset">Stop Animating</li>
  <li id="add">Add to Queue</li>
</ul>
<div style="width:150px; height:150px; background:#ececec;"></div>
JavaScript

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
$('#start').click(animateBox);
 
$('#reset').click(function() {
    $('div').queue('fx', []);
});
 
$('#add').click(function() {
    $('div').queue( function(){
        $(this).animate({ height : '-=25'}, 2000);
        $(this).dequeue();
    });
});
 
function animateBox() {
  $('div').slideUp(2000)
           .slideDown(2000)
           .hide(2000)
           .show(2000, animateBox);
}
So, here's what's going on: in the animateBox function, we're setting up a queue of animations; notice that the last one calls back to the function, so this will continually repeat the queue. When we click li#start, the function is called and the queue begins. When we click li#reset, the current animation finishes, and then the div stops animating. What we've done with jQuery is set the queue named 'fx' (remember, the default queue) to an empty array; essentially, we've emptied the queue. And what about when we click li#add? First, we're calling the queue function on the div; this adds the function we pass into it to the end of the queue; since we didn't specify a queue as the first parameter, 'fx' is used. In that function, we animate the div, and then call dequeue() on the div, which removes this function from the queue and continues the queue; the queue will continue repeating, but this function will not be part of it.

6 delay()
When you're queuing up a chain of animations, you can use the delay() method to pause the animation for a length of time; pass that time as a parameter in milliseconds.

1
$('div').hide().delay(2000).show(); // div will stay hidden for 2 seconds before showing.
7 bind(), unbind(), live(), and die()
Did you know that when you add a click event to an element like this . . .

1
$('#el').click(function () { /*******/ });
. . . you're really just using a wrapper for the bind() method? To use the bind() method itself, you can pass the event type as the first parameter and then the function as the second.

If you use a lot of events, you can categorize them with namespacing; just add a period after the event name and add your namespace.

1
2
$('#el').bind('click', function () { /*******/ });
$('#el').bind('click.toolbarEvents', function () { /*******/ }); // namespaced
You can also assign the same function to multiple events at the same time, by separating them with spaces. So if you wanted to make a hover effect, you could start this way:

1
$('#el').bind('mouseover mouseout', function () { /*******/ });
You can also pass data to the function if you'd like, by adding a third parameter (in the second position).

1
2
3
4
5
$('#el').bind('click', { status : 'user-ready' }, function () {
    switch(event.data.status) {
    /********/
    }
});
Sooner or later, you'll find yourself inserting element into the DOM via an event handler; however, you'll find that the event handlers you've made with bind (or its wrappers) don't work for inserted elements. In cases like this, you'll need to use the live() (or delegate) method; this will add the event handlers to the appropriate inserted elements.

1
2
3
4
5
$('.toggle').live(function () {
    /* code */
    $('<span class="toggle">Enable Beta Features</span>').appendTo($('#optionsPanel'));
    /* more code */
});
To remove event handlers created with bind(), use the unbind() method. If you don't pass it any parameters, it will remove all the handlers; you can pass in the event type to only remove event handlers of that type; to remove events from a specific namespace, add the namespace, or use it alone. If you just want to remove a certain function, pass its name along as the second parameter.

1
2
3
4
5
$('button').unbind(); // removes all
$('button').unbind('click'); // removes all clicks
$('button').unbind('.toolbarEvents'); // removes all events from the toolbarEvents namespace
$('button').unbind('click.toolbarEvents'); // removes all clicks from the toolbarEvents namespace
$('button').unbind('click', myFunction); // removes that one handler
Note that you can bind/unbind functions you've passed in anonymously; this only works with the functions name.
If you're trying to unbind an event from inside the function called by the event, just pass unbind() the event object.

1
2
3
$('p').bind('click', function (event) {
    $('p').unbind(event);
} );
You can't use unbind() for live events; instead, use the die(). Without parameters, it will remove all live events from the element collection; you can also pass it just the event type, of the event type and the function.

1
2
3
$('span').die(); // removes all
$('span').die('mouseover'); // removes all mouseovers
$('span').die('mouseover', fn); // remove that one handler
And now, you can wield jQuery events with deftness and power!

You should also review the delegate() method, as there can be substantial performance benefits to using it over live().

8 eq()
If you're looking for a specific element within a set of elements, you can pass the index of the element to the eq() method and get a single jQuery element. Pass in a negative index to count back from the end of the set.

1
2
3
var ps = $('p');
console.log(ps.length); // logs 3;
ps.eq(1).addClass('emphasis'); // just adds the class to the second item (index in zero-based)
You can also use :eq() in your selectors; so the previous example could have been done like this:

1
$('p:eq(1)').addClass('emphasis');
9 get()
When getting a collection of element, jQuery returns them as a jQuery object, so you have access to all the methods. If you just want the raw DOM elements, you can use the get() method.

You can specify an index to get only one element.

1
2
alert( $('p') ); // [object Object] - the jquery object
alert( $('p').get(1) ); // [object HTMLParagraphElement]
10 grep()
If you're not familiar with Unix/Linix shells, you might not have heard the term grep. In a terminal, it's a text search utility; but here in jQuery, we use it to filter an array of elements. It's not a method of a jQuery collection; you pass in the array as the first parameter and the filtering function as the second parameter. That filter function takes two parameters itself: an element from the array and its index. That filter function should perform its work and return a true or false value. Be default, all the items that return true will be kept. You can add a third parameter, a boolean, to invert the results and kept the items that return false.

Jeffrey Way did a great quick tip about the $.grep not long ago; check that out to see how to use it!

1
2
3
4
5
6
7
8
9
var nums = '1,2,3,4,5,6,7,8,9,10'.split(',');
 
nums = $.grep(nums, function(num, index) {
  // num = the current value for the item in the array
  // index = the index of the item in the array
  return num > 5; // returns a boolean
});
 
console.log(nums) // 6,7,8,9,10
11 Pseudo-Selectors
Sizzle, the CSS Selector engine inside jQuery, offers quite a few pseudo-selectors to make the job of selecting the elements you want easy. Check out these interesting ones:

01
02
03
04
05
06
07
08
09
10
$(':animated'); // returns all elements currently animating
$(':contains(me)'); // returns all elements with the text 'me'
$(':empty'); // returns all elements with no child nodes or text
$(':parent'); // returns all elements with child nodes or text
$('li:even'); // returns all even-index elements (in this case, <li>s)
$('li:odd'); // can you guess?
$(':header'); // returns all h1 - h6s.
$('li:gt(4)'); // returns all elements with an (zero-based) index greater than the given number
$('li:lt(4)'); // returns all element with an index less than the given number
$(':only-child'); // returns all . . . well, it should be obvious
There are more, of course, but these are the unique ones.

12 isArray() / isEmptyObject() / isFunction() / isPlainObject()
Sometimes you want to make sure the parameter that was passed to a function was the corrent type; these functions make it easy to do. The first three are pretty self explanatory:

1
2
3
$.isArray([1, 2, 3]); // returns true
$.isEmptyObject({}); // returns true
$.isFunction(function () { /****/ }); // returns true
The next one isn't as obvious; isPlainObject() will return true if the parameter passed in was created as an object literal, or with new Object().

1
2
3
4
5
6
7
function Person(name) {
    this.name = name
    return this;
}
$.isPlainObject({})); // returns true
$.isPlainObject(new Object()); // returns true
$.isPlainObject(new Person()); // returns false
13 makeArray()
When you create a collection of DOM elements with jQuery, you're returned a jQuery object; in some situations, you might prefer that this be an array or regular DOM elements; the makeArray() function can do just that.

1
2
3
4
var ps = $('p');
$.isArray(ps); //returns false;
ps = $.makeArray(ps);
$.isArray(ps); // returns true;
14 map()
The map() method is remotely similar to grep(). As you might expect, it takes one parameter, a function. That function can have two parameters: the index of the current element and the element itself. Here's what happens: the function that you pass in will be run once for each item in the collection; whatever value is returned from that function takes the place of the item it was run for in the collection.

1
2
3
4
$('ul#nav li a').map(function() {
  return $(this).attr('title');
});  // now the collection is the link titles
// this could be the beginning of a tooltip plugin.
15 parseJSON()
If you're using $.post or $.get—and in other situations that you work with JSON strings—you'll find the parseJSON function useful. It's nice that this function uses the browsers built-in JSON parser if it has one (which will obviously be faster).

$.post('somePage.php', function (data) {
    /*****/
data =  $.parseJSON(data);
    /*****/
});
16 proxy()
If you have a function as a property of an object, and that function uses other properties of the object, you can't call that function from within other functions and get the right results. I know that was confusing, so let's look at a quick example:

1
2
3
4
5
6
7
8
var person = {
  name : "Andrew",
  meet : function () {
    alert('Hi! My name is ' + this.name);
  }
};
person.meet();
$('#test').click(person.meet);
By itself, person.meet() will alert correctly; but when it's called by the event handler, it will alert "Hi! My name is undefined." This is because the function is not being called in the right context. To fix this, we can use the proxy() function:

1
2
$('#test').click($.proxy(person.meet, person));
// we could also do $.proxy(person, "meet")
The first parameter of the proxy function is the method to run; the second is the context we should run it in. Alternatively, we can pass the context first, and the method name as a string second. Now you'll find that the function alerts correctly.

Prefer a video quick tip on $.proxy?

17 replaceAll() / replaceWith()
If you'd like to replace DOM elements with other ones, here's how to do it. We can call replaceAll() on elements we've collected or created, passing in a selector for the elements we'd like to replace. In this example, all elements with the error class will be replaced with the span we've created.

1
$('<span class="fixed">The error has been corrected</span>').replaceAll('.error');
The replaceWith() method just reverses the selectors; find the ones you want to replace first:

1
$('.error').replaceWith('<span class="fixed">The error has been corrected</span>');
You can also pass these two methods functions that will return elements or HTML strings.

18 serialize() / serializeArray()
The serialize() method is what to use for encoding the values in a form into a string.

HTML

1
2
3
4
<form>
    <input type="text" name="name" value="John Doe" />
    <input type="text" name="url" value="http://www.example.com" />
</form>
JavaScript

1
console.log($('form').serialize());​​​ // logs : name=John+Doe&url=http%3A%2F%2Fwww.example.com
You can use serializeArray() to turn the form values into an array of objects instead of a string:

1
2
console.log($('form').serializeArray());​​​
// logs : [{ name : 'name', value : 'John Doe'} , { name : 'url', value : 'http://www.example.com' } ]
19 siblings()
You can probably guess what the siblings() method does; it will return a collection of the siblings of the whatever items are in your original collections:

1
2
3
<div> . . . </div>
<p> . . . </p>
<span> . . . </span>
20 wrap() / wrapAll() / wrapInner()
These three functions make it easy to wrap elements in other elements. First off, I'll mention that all three take one parameter: either an element (which is an HTML string, a CSS selctor, a jQuery object, or a DOM element) or a function that returns an element.
The wrap() method wraps each item in the collection with the assigned element:

1
$('p').wrap('<div class="warning" />'); // all paragraphs are now wrapped in a div.warning
The wrapAll() will wrap one element around all the elements in the collection; this means that the elements in the collection will be moved to a new spot in the DOM; they'll line up at the place of the first element in the collection and be wrapped there:

HTML, Before:

01
02
03
04
05
06
07
08
09
10
<p>
    <span> . . . </span>
    <span class="moveMe"> . . . </span>
    <span class="moveMe"> . . . </span>
</p>
<p>
    <span> . . . </span>
    <span class="moveMe"> . . . </span>
    <span class="moveMe"> . . . </span>
</p>
JavaScript

1
$('.moveMe').wrapAll(document.createElement('div'));
HTML, After:

01
02
03
04
05
06
07
08
09
10
11
12
<p>
    <span> . . . </span>
    <div>
        <span class="moveMe"> . . . </span>
        <span class="moveMe"> . . . </span>
        <span class="moveMe"> . . . </span>
        <span class="moveMe"> . . . </span>
    </div>
</p>
<p>
    <span> . . . </span>
</p>
Finally, the wrapInner function wraps everything inside each element in the collecting with the given element:

HTML, Before:

1
2
3
4
<p>
    <span> . . . </span>
    <span> . . . </span>
</p>
JavaScript:

1
$('p').wrapInner($('<div />'));
HTML, After:

1
2
3
4
5
6
<p>
    <div>
        <span> . . . </span>
        <span> . . . </span>
    </div>
</p>
Conclusion
Well, now you've got more than twenty new jQuery features to play with on your next project; have fun with them!

jQuery.com - "The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks."

With the introduction of HTML5, we can use it as attribute as well. For example

 //We can call it via: $("div").data("role") === "page"; $("div").data("hidden") === true; $("div").data("options").name === "John"; 
The following will work as the above example too:

$("div").data("role", "page"); $("div").data("hidden", "true"); $("div").data("role", {name: "John"}); 
2 .stop( [ clearQueue ], [ jumpToEnd ] )
jQuery.com - "When .stop() is called on an element, the currently-running animation (if any) is immediately stopped. If, for instance, an element is being hidden with .slideUp() when .stop() is called, the element will now still be displayed, but will be a fraction of its previous height. Callback functions are not called."

This method is extremely useful when dealing with animation. It able to terminate all existing animation, and play the most current one.

$(this).find('img').stop(true, true).fadeOut(); 
3 .toggleClass()
jQuery.com - "Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument."

This method allow you to toggle between class, for example, if you have an element with "active" class attached, when this method was used, it will switch it by toggle it on and off (if class exist, remove the class, otherwise put it back on)

$('#home').toggleClass('active'); 
Which is the same with the following:

if ($('#home').hasClass('active')) { $('#home').removeClass('active'); } else { $('#home').addClass('active'); } 
4 .delay( duration, [ queueName ] )
jQuery.com - "Added to jQuery in version 1.4, the .delay() method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue."

This method is really useful to give some delays in a series of animations.

$('#content').slideUp(300).delay(800).fadeIn(400); 
5 .each()
jQuery.com - "The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element."

//Given this HTML Structure 
 
Apple
 
Orange
 
Mango
 
Blueberry
 
Watermelon
 
 //We can retrieve the value with: $('li').each(function(index) { alert(index + ': ' + $(this).text()); }); //Alternatively, loop through JSON var data = "{ name: "John", lang: "JS" }"; $.each( data, function(k, v){ alert( "Key: " + k + ", Value: " + v ); }); 
6 .size()
jQuery.com - "The .size() method is functionally equivalent to the .length property; however, the .length property is preferred because it does not have the overhead of a function call."

But, it still good to know anyway :)

//Given this HTML Structure 
 
Apple
 
Orange
 
Mango
 
Blueberry
 
Watermelon
 
 var size1 = $("li").size(); var size2 = $("li").length; 
Both of the examples above will return 5.

7 .closest(selector)
jQUery.com - Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

$('li.item-a').closest('ul').css('background-color', 'red'); 
8 .position()
jQUery.com - The .position() method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with .offset(), which retrieves the current position relative to the document. When positioning a new element near another one and within the same containing DOM element, .position() is the more useful.

var p = $("p:first"); var position = p.position(); alert("left: " + position.left + ", top: " + position.top); 
1. Hover On/Off
$("a").hover(
  function () {
    // code on hover over
  },
  function () {
    // code on away from hover
  }
);
Source

The jQuery hover method is a quick solution for handling these events. You can determine whether the user is just hovering over your element, or if the user is just leaving the hover state. This allows for two custom functions where you can run two distinct sets of code.

2. Prevent Anchor Links from Loading
$("a").on("click", function(e){
  e.preventDefault();
});
Source

When you create JavaScript applications there are plenty of times where you need a link or button to just do nothing. This is often for triggering some type of dynamic effect, such as a hidden menu or Ajax call. By using the event object during any click, we can manipulate the data sent back to the browser URL. In this scenario I am stopping the whole href from loading anything at all!

3. Scroll to Top
$("a[href='#top']").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;
});
Source

You have probably seen this functionality becoming popular on all the new social networking websites. I have definitely seen this technique appear on infinite-scrolling layouts such as Tumblr and Pinterest.

The code is very minimal but powerful in some layouts. You are offering a simple link or button display which behaves like a “back to home” link. By using the animate effect in jQuery users won’t notice the jump all at once, but instead over a brief period of milliseconds.

4. Ajax Template
$.ajax({
  type: 'POST',
  url: 'backend.php',
  data: "q="+myform.serialize(),
  success: function(data){
    // on success use return data here
  },
  error: function(xhr, type, exception) { 
    // if ajax fails display error alert
    alert("ajax error response type "+type);
  }
});
Source

Passing form data via Ajax is one of the most common uses for jQuery. As a web developer myself I can’t think how many times I am using the ajax method in each project. The syntax can be awfully confusing to memorize, and checking the documentation gets old after a while. Consider copying this small template for usage in any future Ajax-powered webapps.

5. Animate Template
$('p').animate({
    left: '+=90px',
    top: '+=150px',
    opacity: 0.25
  }, 900, 'linear', function() {
    // function code on animation complete
});
Source

As we saw the animate method earlier, this is very powerful for creating dynamic movement on your page. CSS3 transitions are a whole lot easier in some circumstances. But with animate you can manipulate multiple objects or CSS properties all at once!

It’s a very powerful library to get into and start playing with. If you haven’t used any of the jQuery UI library I suggest spending an hour or two practicing with demo stuff. You can animate any object on the page into almost any position or updated style.

6. Toggle CSS Classes
$('nav a').toggleClass('selected');
Source

Adding and removing CSS classes on HTML elements is another fairly common action. This is one technique you may consider with selected menu items, highlighted rows, or active input elements. This newer method is simply quicker than using .addClass() and .removeClass() where you can put all the code into one function call.

7. Toggle Visibility
$("a.register").on("click", function(e){
  $("#signup").fadeToggle(750, "linear");
});
Source

Fading objects out of the document is very common with modern user interfaces. You can always have small popup boxes or notifications which need to display and then hide after a few seconds. Using the fadeToggle function you can quickly hide and display any objects in your DOM. Keep this code handy if you will ever need such functionality in a website interface.

8. Loading External Content
$("#content").load("somefile.html", function(response, status, xhr) {
  // error handling
  if(status == "error") {
    $("#content").html("An error occured: " + xhr.status + " " + xhr.statusText);
  }
});
Source

Believe it or not you can actually pull external HTML code from a file right into your webpage. This doesn’t technically require an Ajax call, but instead we’re parsing the external files for whatever content they have. Afterwards this new content may be loaded into the DOM anywhere in the page.

9. Keystroke Events
$('input').keydown(function(e) {
  // variable e contains keystroke data
  // only accessible with .keydown()
  if(e.which == 11) {
     e.preventDefault();
  }
});

$('input').keyup(function(event) {
  // run other event codes here							  
});
Source

Dealing with user input is another grey area I have come across. The jQuery keydown and keyup event listeners are perfect for dealing with such experiences. Both of these methods are called at very different times during the keystroke event. So make sure you have the application planned out before deciding which one to use.

10. Equal Column Heights
var maxheight = 0;
$("div.col").each(function(){
  if($(this).height() > maxheight) { maxheight = $(this).height(); }
});

$("div.col").height(maxheight);
Source

This is a small jQuery snippet I ran into while surfing the web earlier in the year. While this is not the most recommended solution for your layout display, this code snippet may come in handy down the line. CSS column heights are not always matched and so this dynamic solution using JavaScript is worthy of some insight.

11. Append New HTML
var sometext = "here is more HTML";
$("p#text1").append(sometext); // added after
$("p#text1").prepend(sometext); // added before
Source

Using the .append() method we can quickly place any HTML code directly into the DOM. This is similar to .load() we saw earlier, except these functions can take HTML from any source. You could setup a brand new variable of HTML text or even clone HTML right from your webpage. These properties are often used in conjunction with Ajax response data.

12. Setting & Getting Attributes
var alink = $("a#user").attr("href"); // obtain href attribute value
$("a#user").attr("href", "http://www.google.com/"); // set the href attribute to a new value
$("a#user").attr({
  alt: "the classiest search engine",
  href: "http://www.google.com/"
}); // set more than one attribute to new values
Source

This property is relatively straightforward but I always see these problems in StackOverflow. You can pull the .attr() method on any HTML element and pass in the attribute string value. This will return the value of that attribute, whether it’s ID or class or name or maxlength. All HTML attributes may be accessed through this syntax and so it’s a very powerful method to keep in mind.

13. Retrieve Content Values
$("p").click(function () {
  var htmlstring = $(this).html(); // obtain html string from paragraph
  $(this).text(htmlstring); // overwrite paragraph text with new string value
});
	
var value1 = $('input#username').val(); // textfield input value
var value2 = $('input:checkbox:checked').val(); // get the value from a checked checkbox
var value3 = $('input:radio[name=bar]:checked').val(); // get the value from a set of radio buttons
Source

Instead of appending new HTML content into the document you may also pull out the current HTML content from any area in your webpage. This can be an entire list item block, or the contents of a paragraph tag. Also the .val() property is used on input fields and form elements where you cannot get inside the object to read anything further.

14. Traversing the DOM
$("div#home").prev("div"); // find the div previous in relation to the current div
$("div#home").next("ul"); // find the next ul element after the current div
$("div#home").parent(); // returns the parent container element of the current div
$("div#home").children("p"); // returns only the paragraphs found inside the current div
Source

This idea of traversing through object nodes is deep enough to be an article within itself. But for any intermediate or advance jQuery developers who understand this topic, I’m sure these quick snippets will help in future problem solving.

The goal is often to pull data from another element related to the currently active element(clicked, hovered, etc). This could be the container(parent) element or another inner(child) element, too. There are lots of tools for pulling data from around the DOM so don’t be afraid of experimentation.

Amazing collection of the top 10 most used jQuery snippets that you need to know about! Includes new amazing 1.4 jQuery framework methods.

I have found that people are going bananas over jQuery, so i’ve decided to share my top 10 jQuery snippets that i KNOW you will need to use at one point or another. So here they are, enjoy! I have also added jquery 1.4 features never used before.

1. The quick copy paste jQuery starter embed

Almost every time I start using jQuery I need to paste this in to start writing my beautiful code.

view plaincopy to clipboardprint?
<script src="http://code.jquery.com/jquery-latest.js"></script>  
<script>  
$(document).ready(function(){  
// jQuery Code Here  
});  
</script>  
You can either paste this in your header (if you are using jquery for any appearance changes its suggested to do so in the header) or you can add it at the end of your body, that way your styles will load first (hence making a faster load) and then the jquery will be loaded last.

2. Value swap (usually for search fields)

I find myself using this rather often, whenever you have a search field and you want it to defaultly display a value “search…” and have that value empty out on focus, well this is how to do this with jQuery 1.4.

view plaincopy to clipboardprint?
swap_val = [];  
$(".swap").each(function(i){  
swap_val[i] = $(this).val();  
$(this).focusin(function(){  
if ($(this).val() == swap_val[i]) {  
$(this).val("");  
}  
}).focusout(function(){  
if ($.trim($(this).val()) == "") {  
$(this).val(swap_val[i]);  
}  
});  
});  
This jquery will create an array with every input field that has the class swap. For example:

view plaincopy to clipboardprint?
<input type="text" class="swap" value="Swap Me!" />  
The value Swap Me! will be erased when you click in the input field, and it will come back in if you don’t enter anything.

3. Equal Column Height

Unfortunately css does not support this natively, sometimes when creating column based layouts it looks so much better if the columns aligned by height, so here is the easy way of doing this.

view plaincopy to clipboardprint?
var max_height = 0;  
$("div.col").each(function(){  
if ($(this).height() > max_height) { max_height = $(this).height(); }  
});  
$("div.col").height(max_height);  
This will go through every div with class col and check for which one contains the highest size, once done it will apply that height to all divs with class col. For example:

view plaincopy to clipboardprint?
<div style="height:200px;" class="col"></div><!-- this being the higher div will be set as the max_height -->  
<div class="col"></div><!-- this being the smaller div will be made 200px high -->  
If you read the comments above you will see that each div has the class col, and that the second div will be set at height 200px.

4. On Hover add and Remove a class

Let’s say you want to have a suckerfish dropdown, or maybe you just want to add a cool hover on a div, well in some browsers thats not allowed to be done with pure css, hence use this simple technique and you will have cross browser hover with any two class you want.

view plaincopy to clipboardprint?
$('.onhover').hover(  
function(){ $(this).addClass('hover_style_class') },  
function(){ $(this).removeClass('hover_style_class') }  
)  
The code above will apply a class home_style_class on hover of an element with the class onhover.

5. Live Event Binding

With jquery you can capture an onclick event with the .click() method, but this is the slower less efficient way. Also if you created new elements with ajax or with jquery those new elements will not be bound by the regular click() method. So using live click/submit and so on will apply itself to all new elements, and will only bind once to all.

view plaincopy to clipboardprint?
$(".element").live("click", function(){  
// do something on click  
});  
The code above will apply any code you want on click event on an element with class element.

6. Partial Page Refresh

Okay personally when the term ajax comes to mind i get a little worried… but I found this amazing technique to refresh page content without any real ajax or special tricks. All you need is to apply an id to a certain element, and run this little script, choose how many seconds to wait until refresh and VUALA!

view plaincopy to clipboardprint?
setInterval(function() {  
$("#refresh").load(location.href+" #refresh>*","");  
}, 10000); // seconds to wait, miliseconds  
Okay so the script above will refresh the div with id refresh every 10 seconds… this can be so awesome in so many cases! Btw make sure you have tags inside the refresh div, otherwise it doesn’t seem to work with pure text.

7. Each Element

I seem to use this pretty often when i want to do something with a set of elements, for example if you do your own form validation and you want to check each input field before submitting.

view plaincopy to clipboardprint?
$("input").each(function (i) {  
//do something with each and pass i as the number of the element  
});  
So choose an element to cycle through, it can be a set of li’s in a chosen unordered list, or all the input fields as above. Use the i to get the number of the current element, and of course the $(this) to do something to the element it’s going through.

8. Find an element close by (jQuery 1.4)

With the new jQuery 1.4 we have the new awesome feature of the closest() method which will find the element closes to the current one. So no more searching through the parents and children to get to the close element we need.

view plaincopy to clipboardprint?
$("li").click(function(){  
$(this).closest(".me").addClass("smile");  
});  
The code above will find the closes class me to the li that was clicked on and add class smile to it. Hence you can see how beneficial this can be!

9. Delay animation/effect

Another great new feature of the 1.4 jquery framework is the Delay method which allows you to delay an animation. Instead of using the setTimeout method, you can now simply add the .delay() method and pass in how long to delay, like this:

view plaincopy to clipboardprint?
$(".alert").delay(2000).fadeOut();  
The above will fade out an element with class alert after 2 seconds. This can be used for growl like notifications.

10. Check if an element contains a certain class or element

Another awesome feature of jQuery 1.4 that will be quite handy is the has method. This method will find if a an element contains a certain other element class or whatever it is you are looking for and do anything you want to them.

view plaincopy to clipboardprint?
$("input").has(".email").addClass("email_icon");  
In the above code we will look through all inputs that have the class email and add the class email_icon.

Here are some that didn’t make the top 10 cut:

Creating the zebra stripe effect on UL/OL or Tables

Sometimes we have tables or ordered/unordered lists that we want to be easily read. Here is a quick jq trick:

view plaincopy to clipboardprint?
$("tr:odd").addClass("odd");  
$("li:odd").addClass("odd");  
The code will add the class odd to every other element!

Automatic external link open in New Window

Tired of having to add target=”_blank” every time you don’t want your visitors to navigate away from your page? Let jquery do the work!

view plaincopy to clipboardprint?
$('a').each(function() {  
var a = new RegExp('/' + [removed].host + '/');  
if(!a.test(this.href)) {  
$(this).click(function(event) {  
event.preventDefault();  
event.stopPropagation();  
window.open(this.href, '_blank');  
});  
}  
});  
Now every a href in your page will open in a new window if it doesnt go somewhere in your own website!

1. Preloading Images
view source

print?
0001	(function($) {
0002	  var cache = [];
0003	  // Arguments are image paths relative to the current page.
0004	  $.preLoadImages = function() {
0005	    var args_len = arguments.length;
0006	    for (var i = args_len; i--;) {
0007	      var cacheImage = document.createElement('img');
0008	      cacheImage.src = arguments[i];
0009	      cache.push(cacheImage);
0010	    }
0011	  }
0012	 
0013	jQuery.preLoadImages("image1.gif", "/path/to/image2.png");
 
Source  

2. Make Everything Mobile Friendly
view source

print?
0001	var scr = document.createElement('script');
0002	scr.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js');
0003	document.body.appendChild(scr);
0004	 
0005	scr.onload = function(){
0006	     
0007	    $('div').attr('class', '').attr('id', '').css({
0008	        'margin' : 0,
0009	        'padding' : 0,
0010	        'width': '100%',
0011	        'clear':'both'
0012	    });
0013	};
 
Source  

3. Image Resizing Using jQuery
view source

print?
0001	$(window).bind("load", function() {
0002	    // IMAGE RESIZE
0003	    $('#product_cat_list img').each(function() {
0004	        var maxWidth = 120;
0005	        var maxHeight = 120;
0006	        var ratio = 0;
0007	        var width = $(this).width();
0008	        var height = $(this).height();
0009	 
0010	        if(width &gt; maxWidth){
0011	            ratio = maxWidth / width;
0012	            $(this).css("width", maxWidth);
0013	            $(this).css("height", height * ratio);
0014	            height = height * ratio;
0015	        }
0016	        var width = $(this).width();
0017	        var height = $(this).height();
0018	        if(height &gt; maxHeight){
0019	            ratio = maxHeight / height;
0020	            $(this).css("height", maxHeight);
0021	            $(this).css("width", width * ratio);
0022	            width = width * ratio;
0023	        }
0024	    });
0025	    //$("#contentpage img").show();
0026	    // IMAGE RESIZE
0027	});
 
Source  

4. Back To Top Link
view source

print?
0001	// Back To Top
0002	$(document).ready(function(){
0003	  $('.top').click(function() { 
0004	     $(document).scrollTo(0,500); 
0005	  });
0006	});
0007	 
0008	//Create a link defined with the class .top
0009	&lt;a href="#" class="top"&gt;Back To Top&lt;/a&gt;
 
Source  

5. jQuery Accordion
view source

print?
0001	var accordion = {
0002	     init: function(){
0003	           var $container = $('#accordion');
0004	           $container.find('li:not(:first) .details').hide();
0005	           $container.find('li:first').addClass('active');
0006	           $container.on('click','li a',function(e){
0007	                  e.preventDefault();
0008	                  var $this = $(this).parents('li');
0009	                  if($this.hasClass('active')){
0010	                         if($('.details').is(':visible')) {
0011	                                $this.find('.details').slideUp();
0012	                         } else {
0013	                                $this.find('.details').slideDown();
0014	                         }
0015	                  } else {
0016	                         $container.find('li.active .details').slideUp();
0017	                         $container.find('li').removeClass('active');
0018	                         $this.addClass('active');
0019	                         $this.find('.details').slideDown();
0020	                  }
0021	           });
0022	     }
0023	};
 

6. Emulate Facebook by Preloading Previous & Next Photo Gallery Images
view source

print?
0001	var nextimage = "/images/some-image.jpg";
0002	$(document).ready(function(){
0003	window.setTimeout(function(){
0004	var img = $("<img alt="" />").attr("src", nextimage).load(function(){
0005	//all done
0006	});
0007	}, 100);
0008	});
 
Source  

7. Auto Populating Select Boxes Using jQuery & Ajax
view source

print?
0001	$(function(){
0002	$("select#ctlJob").change(function(){
0003	$.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
0004	var options = '';
0005	for (var i = 0; i &lt; j.length; i++) {
0006	options += '
0007	' + j[i].optionDisplay + '
0008	 
0009	';
0010	}
0011	$("select#ctlPerson").html(options);
0012	})
0013	})
0014	})
 
Source  

8. Auto-Replace Broken Images
view source

print?
0001	// Safe Snippet
0002	$("img").error(function () {
0003	    $(this).unbind("error").attr("src", "missing_image.gif");
0004	});
0005	 
0006	// Persistent Snipper
0007	$("img").error(function () {
0008	    $(this).attr("src", "missing_image.gif");
0009	});
 
Source  

9. Fade In/Out on Hover
view source

print?
0001	$(document).ready(function(){
0002	    $(".thumbs img").fadeTo("slow", 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads
0003	 
0004	    $(".thumbs img").hover(function(){
0005	        $(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover
0006	    },function(){
0007	        $(this).fadeTo("slow", 0.6); // This should set the opacity back to 60% on mouseout
0008	    });
0009	});
 
Source  

10. Clear Form Data
view source

print?
0001	function clearForm(form) {
0002	  // iterate over all of the inputs for the form
0003	  // element that was passed in
0004	  $(':input', form).each(function() {
0005	    var type = this.type;
0006	    var tag = this.tagName.toLowerCase(); // normalize case
0007	    // it's ok to reset the value attr of text inputs,
0008	    // password inputs, and textareas
0009	    if (type == 'text' || type == 'password' || tag == 'textarea')
0010	      this.value = "";
0011	    // checkboxes and radios need to have their checked state cleared
0012	    // but should *not* have their 'value' changed
0013	    else if (type == 'checkbox' || type == 'radio')
0014	      this.checked = false;
0015	    // select elements need to have their 'selectedIndex' property set to -1
0016	    // (this works for both single and multiple select elements)
0017	    else if (tag == 'select')
0018	      this.selectedIndex = -1;
0019	  });
0020	};
 
Source  

11. Prevent Multiple Submit of Your Form
view source

print?
0001	$(document).ready(function() {
0002	  $('form').submit(function() {
0003	    if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
0004	      jQuery.data(this, "disabledOnSubmit", { submited: true });
0005	      $('input[type=submit], input[type=button]', this).each(function() {
0006	        $(this).attr("disabled", "disabled");
0007	      });
0008	      return true;
0009	    }
0010	    else
0011	    {
0012	      return false;
0013	    }
0014	  });
0015	});
 
Source  

12. Dynamically Add Form Elements
view source

print?
0001	//change event on password1 field to prompt new input
0002	$('#password1').change(function() {
0003	        //dynamically create new input and insert after password1
0004	        $("#password1").append("<input id="password2" type="text" name="password2" />");
0005	});
 
Source  

13. Make Entire Div Clickable
view source

print?
0001	<div class="myBox">blah blah blah. <a href="http://google.com">link</a></div>
0002	The following lines of jQuery will make the entire div clickable: $(".myBox").click(function(){ window.location=$(this).find("a").attr("href"); return false; });
 
Source  

14. Equalize height or Div Elements
view source

print?
0001	var maxHeight = 0;
0002	 
0003	$("div").each(function(){
0004	   if ($(this).height() &gt; maxHeight) { maxHeight = $(this).height(); }
0005	});
0006	 
0007	$("div").height(maxHeight);
 
Source  
Tagged: