20 Top jQuery tips & tricks for jQuery programmers

Following are few very useful jQuery Tips and Tricks for all jQuery developers.

1. Optimize performance of complex selectors

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

1.var subset = $("");

2.$("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.

1.$("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:

1.$('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:

1.$('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

1.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:

1.$("ul > li").click(function ()

2.{
3. var index = $(this).prevAll().length;
4.});

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.

1.$("#myButton").click(function() {

2. $("#myDiv").fadeTo("slow", 0.01, function(){ //fade
3. $(this).slideUp("slow", function() { //slide up
4. $(this).remove(); //then remove from the DOM
5. });
6. });
7.});

7. Checking if an element exists

Use following snippet to check whether an element exists or not.

1.if ($("#someDiv").length) {

2. //hooray!!! it exists...
3.}

8. Add dynamically created elements into the DOM

Use following code snippet to create a DIV dynamically and add it into the DOM.

1.var newDiv = $('<div></div>');

2.newDiv.attr("id","myNewDiv").appendTo("body");

9. Line breaks and chainability

Instead of doing:

1.$("a").hide().addClass().fadeIn().hide();

You can increase readability like so:

1.$("a")

2. .hide()
3. .addClass()
4. .fadeIn()
5. .hide();

10. Creating custom selectors

01.$.extend($.expr[':'], {

02. over100pixels: function(a) {
03. return $(a).height() > 100;
04. }
05.});
06.
07.$('.box:over100pixels').click(function() {
08. alert('The element you clicked is over 100 pixels high');
09.});

11. Cloning an object in jQuery

Use .clone() method of jQuery to clone any DOM object in JavaScript.

1.// Clone the DIV

2.var cloned = $('#somediv').clone();

jQuery’s clone() method does not clone a JavaScript object. To clone JavaScript object, use following code.

1.// Shallow copy

2.var newObject = jQuery.extend({}, oldObject);
3.
4.// Deep copy
5.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.

1.if($(element).is(":visible") == "true") {

2. //The element is Visible
3.}

13. Alternate way of Document Ready

1.//Instead of

2.$(document).ready(function() {
3. //document ready
4.});
5.//Use
6.$(function(){
7. //document ready
8.});

14. Selecting an element with . (period) in its ID

Use backslash in the selector to select the element having period in its ID.

1.$("#Address\\.Street").text("Enter this field");

15. Counting immediate child elements

If you want to count all the DIVs present in the element #foo

01.<div id="foo">

02. <div id="bar"></div>
03. <div id="baz">
04. <div id="biz">
05. </div>
06. <span><span>
07.</div>
08.
09.//jQuery code to count child elements
10.$("#foo > div").size()

16. Make an element to “FLASH”

1.jQuery.fn.flash = function( color, duration )

2.{
3. var current = this.css( 'color' );
4. this.animate( { color: 'rgb(' + color + ')' }, duration / 2 );
5. this.animate( { color: current }, duration / 2 );
6.}
7.//Then use the above function as:
8.$( '#importantElement' ).flash( '255,0,0', 1000 );

17. Center an element on the Screen

01.jQuery.fn.center = function () {

02. this.css("position","absolute");
03. this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
04. this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
05. return this;
06.}
07.
08.//Use the above function as:
09.$(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:

1.$("#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:

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

2. $(document).bind("contextmenu",function(e){
3. return false;
4. });
5.});

20. Get mouse cursor x and y axis

This script will display the x and y value – the coordinate of the mouse pointer.

1.$().mousemove(function(e){

2. //display the x and y axis values inside the P element
3. $('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
4.});
5.
6.<p></p>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s