20 Top jQuery Tips & Tricks for jQuery Programmers

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>  


44 Comments

  • Andrew 17 August, 2009, 19:48

    Thanks for sharing these tips, very useful. I think readers would find this 5 jquery performance tips useful:

    http://jquery-howto.blogspot.com/2009/02/5-easy-tips-on-how-to-improve-code.html

  • Dan Wellman 17 August, 2009, 19:54

    Great list :D

    Couple of things though:

    number 7 – while that does work, you don’t need to check whether elements exist before selecting them. jQuery will not throw errors if you try to select elements not on the page (unlike most other libraries). Unnecessary checking of whether elements exist will slow things down a little.

    number 9 – this is in no way related to performance, in fact, it may even make scripts slower! Compression applications, such as YUI compressor, remove line-breaks from JS documents when you compress them. Line breaks do need to be processed and exist as characters, so unecessary line breaks are going to slow things down (even only by a few milliseconds)

    But some great tips apart from those :)

  • Viral Patel 17 August, 2009, 20:06

    @Andrew, Thanks for the comment and thanks for sharing the useful link.

    @Dan, Great insight and thanks for the comment :) Glad you liked the snippets. Feel free to go through rest of the articles of this site.

  • heyyeah 18 August, 2009, 16:42

    Great list, thanks. I’m may quesion #17, how to replicate being in top 20 but I’d just be quibbling :)

  • Majnun 19 August, 2009, 0:07

    @Dan: Regarding #9, you must admit that the virtually unnoticeable drop in speed is well worth the upgrade to readability

  • Vipul Limbachiya 19 August, 2009, 12:28

    Good list! thanks for sharing

  • Viral Patel 19 August, 2009, 14:00

    @Vipul, Thanks for the comment. Happy Reading :)

  • Kyle Farris 19 August, 2009, 22:43

    I’ve been using jQuery for about as long as it has existed (about 3-4 years) and I never knew there was “contextmenu” event. Never had to use it… but, it’s nice to know it exists.

  • Acaz 20 August, 2009, 19:52

    The item 13 is not good in performance.

  • Shahriar Hyder 24 September, 2009, 14:15

    Nice collection of jQuery Tips and Tricks mate. I have also linked to yours from my blog post below where I am trying to collect the most useful and common jQuery code snippets for JavaScript over the web. Here is the title and the link to the jQuery link compilation endeavor:

    Ultimate collection of top jQuery tutorials, tips-tricks and techniques to improve performance

    http://technosiastic.wordpress.com/2009/09/24/collection-of-top-jquery-tutorials-tips-tricks-techniques-to-improve-performance/

  • TopFreewareDownload.com 17 October, 2009, 7:47

    The tutor is very good …….

  • مهپویا 21 January, 2010, 2:15

    very powerful

  • willy 22 February, 2010, 15:09

    Thank you!happy reading…

  • Arvind 12 June, 2010, 22:55

    Nice tutorial.
    For more Jquery tutorials visit webspeaks.in

  • Frank 7 October, 2010, 11:29

    I tried #16 and it is not working. I found out that jQuery does not allow color property to be changed in .animate(). Any idea?

    • BadMonkey0001 23 June, 2012, 6:32

      You’ll need the jQuery UI code to animate non-numeric values now. You don’t need all the jQUI theme stuff, just the JS file.

  • Raghunath 7 January, 2011, 0:45

    Its very useful information..good one.

  • papay 15 February, 2011, 13:05

    Thanks for this list. especially for #17. Great tips!

  • ενοικίαση αυτοκινήτου κύθηρα 31 March, 2011, 5:25

    Nice tips and guides. Very useful.
    Thanks for the list.

  • Kyathi 3 May, 2011, 10:00

    Excellent art of knowledge. :-)

    • sanju dahiya 6 December, 2011, 13:49

      yaa reaaaly nice

  • Hosting Best 17 May, 2011, 15:49

    Interesting alternative for the page loaded function, nice work!

  • Suanne Brennen 18 June, 2011, 3:15

    Thank you a lot for giving everyone an exceptionally nice possiblity to read articles and blog posts from here. It can be so nice and as well , full of a great time for me personally and my office co-workers to visit your website at minimum 3 times a week to find out the newest guides you have. And indeed, I’m also always impressed for the unbelievable techniques served by you. Some 3 ideas in this article are undeniably the simplest I have had.

  • Karissa Rougeau 4 July, 2011, 2:21

    Keep working ,great job!

  • Vijaya Anand 10 September, 2011, 14:17

    Nice article. I also wrote a small article about this subject http://www.prideparrot.com/blog/archive/2011/9/interesting_things_from_jquery

  • Mike 20 October, 2011, 1:23

    I like #19 will defenatly use it

  • dipak kumar burnwal 2 November, 2011, 19:02

    great tips really helpful

  • Virendra 28 November, 2011, 11:36

    Great post.. But today i found something new about how to use selectors efficiently, which is really a great post indeed..

    Thought of sharing with your reader.
    http://jquerybyexample.blogspot.com/2011/11/tips-to-use-jquery-selectors.html

    Thanks,
    Virendra

  • Mark 20 December, 2011, 10:21

    I must admit it is a great list indeed. I am collecting jquery tips and tricks. I follow a jquery blog called jquerybyexample.blogspot.com. Recently this guy has also posted about top jquery tips and tricks. few are similar to yours but rest of them are really worth.

    http://jquerybyexample.blogspot.com/2011/12/best-jquery-tips-and-tricks.html

  • Mark 20 December, 2011, 10:21

    And yes forgot to mention that I have started following your blog as well…

  • Bhupendra Singh Parihar 25 January, 2012, 19:16

    Its great that you collected most commnly used tricks of JQuery. I have been using few of them and this list really helped me. One of the common use is to make select the first drop down.

    $(“target option:first”).attr(‘selected’,’selected’);
    or
    $(“#target”).val($(“#target option:first”).val());

  • Manish Choudhary 20 February, 2012, 14:08

    Awesome tips specially 16 and17

  • Rafael 26 March, 2012, 22:44

    Really good and usefull collection. Thank you.

  • Adam 12 April, 2012, 11:45

    Great tips! Trying to get a grasp on jQuery and found that very useful.

  • manikandan 17 April, 2012, 21:06

    This is awesome. It will be very helpful for the beginners like me.
    Thank you very much for giving such as a wonderful article/

  • Derrick 21 June, 2012, 23:53

    #6 can be done like this – using delay().

    $(“#myButton”).click(function() {
    $(“#myDiv”).fadeTo(500, 0.01).delay(500).slideUp(500).delay(500).remove();
    });

  • Timothy McClanahan 22 June, 2012, 1:44

    Regarding #19, don’t ever do that. That’s actively user hostile. No no no.

  • علیرضا 22 June, 2012, 12:01

    Man you’re awesome! did you know about it? ;)
    very well-organized collection, thanks dude.

  • XF 22 June, 2012, 17:17

    in 15. with this method :

     

    you have $(“#foo > div”).size() = 1

  • BadMonkey0001 23 June, 2012, 6:41

    $.fn.live() is dperecated. Please don’t use it.

  • Maria 3 December, 2012, 4:34

    This is a great jquery tutorials, thanks for sharing!

  • Mercury 1 April, 2013, 20:30

    Very helpful! I found 1 mistake though.

    Instead of:

    var newObject = jQuery.extend(true, {}, oldObject);

    you should use:

    var newObject;
    jQuery.extend(true, newObject, oldObject);

    Especially if you’re working with json data (I had a json list), it messes it up:
    This:

    data: [{property1:"value1",property2:value2}, { ... }]

    becomes this:

    ({0:{property1:"value1", property2:value2}, 1:{ ... }})
  • Mahmoud Saeed 2 June, 2014, 18:48

    Thanks you, it is a good tips,
    nice work

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current day month ye@r *