Introduction:
jQuery is a simple, light-weight, open source, cross browser JavaScript library that simplifies event handling, animations and developing Ajax-enabled web applications and promotes rapid application development. In this article we will discuss some useful tips and tricks in jQuery.
Following are few very useful jQuery Tips and Tricks for all jQuery developers. It will be very useful to you.
You can download the jQuery library here.
1- Disabling Right Mouse Click
2- Optimize performance of complex selectors
Query a subset of the DOM when using complex selectors drastically improves performance:
3- 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.
4- 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:
5- 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:
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:
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
6- 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:
------------------------------------------------------------------OR--------------------------------------------------------
7- 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
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:
8- Check if an Element Exists
To check whether an element exists, you can write the following code:
9. 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.
10- 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.
11- Set a Timer
The following piece of code can be used to set a timer using jQuery:
12- jQuery's Chaining Feature
Chaining is a great feature in jQuery that allows you to chain method calls. Here is an example:
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:
13- 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:
14- 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:
15- Fadeout Slideup effect to remove an element
Combine more than one effects in jQuery to animate and remove an element from DOM.
16- 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
17- Line breaks and chainability
Instead of doing:
You can increase readability like so:
18- Creating custom selectors
19- Cloning an object in jQuery
Use .clone() method of jQuery to clone any DOM object in JavaScript.
jQuery’s clone() method does not clone a JavaScript object. To clone JavaScript object, use following code.
20- Alternate way of Document Ready
21- Selecting an element with . (period) in its ID
Use backslash in the selector to select the element having period in its ID.
22- Counting immediate child elements
If you want to count all the DIVs present in the element #foo
23- Make an element to “FLASH”
24- Center an element on the Screen
25. 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:
jQuery is a simple, light-weight, open source, cross browser JavaScript library that simplifies event handling, animations and developing Ajax-enabled web applications and promotes rapid application development. In this article we will discuss some useful tips and tricks in jQuery.
Following are few very useful jQuery Tips and Tricks for all jQuery developers. It will be very useful to you.
You can download the jQuery library here.
1- Disabling Right Mouse Click
$(document).ready(function(){ $(document).bind("contextmenu",function(e){ return false; }); });
2- Optimize performance of complex selectors
Query a subset of the DOM when using complex selectors drastically improves performance:
var subset = $(""); $("input[value^='']", subset);
3- 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]);
4- 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 } });
5- 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
6- 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> });
------------------------------------------------------------------OR--------------------------------------------------------
$().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>
7- 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; });
8- 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 }
9. 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.
10- 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 DOM element is visible } else { //The DOM element is invisible }
11- 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); });
12- 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');
13- 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();
14- 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…'); });
15- 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 }); }); });
16- 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")
17- Line breaks and chainability
Instead of doing:
$("a").hide().addClass().fadeIn().hide();
You can increase readability like so:
$("a")
.hide()
.addClass()
.fadeIn()
.hide();
18- 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'); });
19- 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);
20- Alternate way of Document Ready
//Instead of $(document).ready(function() { //document ready }); //Use $(function(){ //document ready });
21- 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");
22- 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()
23- 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 );
24- 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();
25. 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");
No comments:
Post a Comment