JQuery - Tips

From Catglobe Wiki
Revision as of 11:22, 22 April 2010 by Catglobe (talk | contribs) (Created page with '*** under contruction Following 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: …')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
      • under contruction

Following 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: view source print? 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. view source print? 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: view source print? 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: view source print? 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 view source print? 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: view source print? 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. view source print? 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. view source print? 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. Further Reading: Dynamically Add/Remove rows in HTML table using JavaScript view source print?

1 var newDiv = $('

');

2 newDiv.attr("id","myNewDiv").appendTo("body"); 9. Line breaks and chainability

Instead of doing: view source print? 1 $("a").hide().addClass().fadeIn().hide();

You can increase readability like so: view source print? 1 $("a") 2 .hide() 3 .addClass() 4 .fadeIn() 5 .hide(); 10. Creating custom selectors view source print? 1 $.extend($.expr[':'], { 2 over100pixels: function(a) { 3 return $(a).height() > 100; 4 } 5 }); 6 7 $('.box:over100pixels').click(function() { 8 alert('The element you clicked is over 100 pixels high'); 9 }); 11. Cloning an object in jQuery

Use .clone() method of jQuery to clone any DOM object in JavaScript. view source print? 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. view source print? 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. view source print? 1 if($(element).is(":visible") == "true") { 2 //The element is Visible 3 } 13. Alternate way of Document Ready view source print? 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. view source print? 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 view source print?

01

02
03
04
05

06

07

08 09 //jQuery code to count child elements 10 $("#foo > div").size() 16. Make an element to “FLASH” view source print? 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 view source print? 1 jQuery.fn.center = function () { 2 this.css("position","absolute"); 3 this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px"); 4 this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px"); 5 return this; 6 } 7 8 //Use the above function as: 9 $(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: view source print? 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: view source print? 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. view source print? 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