1. jQuery $(document).ready shorthand
This is a great tip! Instead of doing this
$(document).ready(function() {
//write your code here
}
You can also do this, both are the same!
$(function(){
//write your code here
});
2. Switch to different CSS style sheets
You want to have different design for your website. You can use this to switch to different CSS Style Sheets:
$("a.cssSwitcher]").click(function() {
//swicth the LINK REL attribute with the value in A REL attribute
$("link[rel=stylesheet]").attr({href : this.attr(rel)});
});
<link rel="stylesheet" href="default.css" type="text/css">
......
<a href="#" class="cssSwitcher" rel="default.css">Default Theme</a>
<a href="#" class="cssSwitcher" rel="red.css">Red Theme</a>
<a href="#" class="cssSwitcher" rel="blue.css">Blue Theme</a>
3. Disable right click
Some of us might want to disable right click, or want to create our own context menu for the website, this is how we can detect right click:
$(document).bind("contextmenu",function(e){
//you can enter your code here, e.g a menu list
//cancel the default context menu
return false;
});
4. Text Resizing With jQuery
Ever wondered how to allow visitors to increase or decrease the text size (font size) on your website? I’m going to show you how – using jQuery (a great JavaScript library).
$(document).ready(function(){
//ID, class and tag element that font size is adjustable in this array
//Put in html or body if you want the font of the entire page adjustable
var section = new Array('span','.section2');
section = section.join(',');
// Reset Font Size
var originalFontSize = $(section).css('font-size');
$(".resetFont").click(function(){
$(section).css('font-size', originalFontSize);
});
// Increase Font Size
$(".increaseFont").click(function(){
var currentFontSize = $(section).css('font-size');
var currentFontSizeNum = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSizeNum*1.2;
$(section).css('font-size', newFontSize);
return false;
});
// Decrease Font Size
$(".decreaseFont").click(function(){
var currentFontSize = $(section).css('font-size');
var currentFontSizeNum = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSizeNum*0.8;
$(section).css('font-size', newFontSize);
return false;
});
});
<a class="increaseFont">+</a> |
<a class="decreaseFont">-</a> |
<a class="resetFont">=</a>
<span>Font size can be changed in this section</span>
<div class="section1">This won't be affected</div>
<div class="section2">This one is adjustable too!</div>
5. How to disabled/enable an element with jQuery
// To disable
$('.someElement').attr('disabled', 'disabled');
// To enable
$('.someElement').removeAttr('disabled');
// OR you can set attr to ""
$('.someElement').attr('disabled', '');
6. Let Google host jQuery for you
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function() {
//Code to be inserted in this area
});
</script>
/* the best way (fastest and most efficient implementation) */
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//This is more like it!
});
</script>
7. No conflict-mode
jQuery.noConflict();
“Run this function to give control of the $ variable back to whichever library first implemented it. This helps to make sure that jQuery doesn’t conflict with the $ object of other libraries.
By using this function, you will only be able to access jQuery using the jQuery variable. For example, where you used to do $(”div p”), you now must do jQuery(”div p”)”.
8. Line breaks and chainability
Instead of doing:
$("a").hide().addClass().fadeIn().hide();
You can increase readability like so:
$("a")
.hide()
.addClass()
.fadeIn()
.hide();
9. Write our own selector
//extend the jQuery functionality
$.extend($.expr[':'], {
//name of your special selector
moreThanAThousand : function (a){
//Matching element
return parseInt($(a).html()) > 1000;
}
});
$(document).ready(function() {
$('td:moreThanAThousand').css('background-color', '#ff0000');
});
<TABLE>
<table>
<tbody>
<tr><td>1400</td><td>700</td><td>400</td></tr>
<tr><td>2500</td><td>600</td><td>100</td></tr>
<tr><td>100</td><td>1100</td><td>900</td></tr>
<tr><td>2600</td><td>1100</td><td>1200</td></tr>
</tbody>
</table>
</TABLE>
10. Columns of equal height
$(document).ready(function() {
setHeight('.col');
});
//global variable, this will store the highest height value
var maxHeight = 0;
function setHeight(col) {
//Get all the element with class = col
col = $(col);
//Loop all the col
col.each(function() {
//Store the highest value
if($(this).height() > maxHeight) {
maxHeight = $(this).height();;
}
});
//Set the height
col.height(maxHeight);
}
<div class="col" style="border:1px solid">Column One<br/>
With Two Line<br/>
And the height is different<br/><br/>
</div>
<div class="col" style="border:1px solid">Column Two<br/><br/></div>
11. Back to top button/link
With this plugin, you will easily scroll overflowed elements, and the screen itself.
It gives you access to many different options to customize and various ways to specify where to scroll.
$('#top').click(function() {
$(document).scrollTo(0,500);
}
<script type="text/javascript" src="js/jquery.scrollTo-min.js"></script>
......
<a id="top" style="cursor:hand;cursor:pointer">
Back to top
12. Prevent default behaviour
Assuming we have a long page, and we have a link similar to below that is used for other purposes other than a hyperlink. If you clicked on it, it will bring you to the top of your page. The reason of this behavior is because of the # symbol. To solve this problem, we need to cancel the default behavior by doing this:
$('#close').click(function(e){
e.preventDefault();
});
/* OR */
$('#close').click(function(){
return false;
});
<a href="#" id="close"></a>
13. 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>
14. Open in new window
Target attribute is not valid in STRICT W3C standard. Thus, we need to use REL and a bit of jQuery code to dynamically create the attribute to avoid validation error. This is one of my favourite codes. It’s so simple and does the job well.
$('a[rel=external]').attr('target','_blank');
<a href="http://www.queness.com" rel="external">Queness in new window</a>
15. Check if checkbox is checked
jQuery provides us 3 ways to determine if a checkbox is checked.
// First way
$('#checkBox').attr('checked');
// Second way
$('#edit-checkbox-id').is(':checked');
// Third way
$("[:checkbox]:checked").each(
function() {
// Insert code here
}
);
jQuery is a great library but I had a hard time to identify if it was checked at the time. So here is the way to do just that. All you need to do is to check checked attribute of an HTML tag:
// First way
$('#checkBox').attr('checked');
// Second way
$('#edit-checkbox-id').is(':checked');
// Third way
$("input[@type=checkbox][@checked]").each(
function() {
// Insert code here
}
);
16. Check if jQuery.js is loaded
/* Method 1 */
if (jQuery) {
// jQuery is loaded
} else {
// jQuery is not loaded
}
/* Method 2 */
if (typeof jQuery == 'undefined') {
// jQuery is not loaded
} else {
// jQuery is loaded
}
17. Target blank links
Do you use the target=blank attribute on links? If yes, you might know that XHTML 1.0 Strict don’t allow it. A good solution to this problem should be using JQuery to make links opening in new windows:
$('a[@rel$='external']').click(function(){
this.target = "_blank";
});
/*
Usage:
<a href="http://www.lepinskidesign.com.br/" rel="external">lepinskidesign.com.br</a>
*/
18. Preloading images
When you’re using images in Javascript, a good thing is to preload it before you have to use it. This code will do the job:
jQuery.preloadImages = function()
{
for(var i = 0; i").attr("src", arguments[i]);
}
};
// Usage
$.preloadImages("image1.gif", "/path/to/image2.png", "some/image3.jpg");
19. Detect browser
Although it is better to use CSS conditionnal comments to detect a specific browser and apply some css style, it is a very easy thing to do with JQuery, which can be useful at times.
//A. Target Safari
if( $.browser.safari ) $("#menu li a").css("padding", "1em 1.2em" );
//B. Target anything above IE6
if ($.browser.msie && $.browser.version > 6 ) $("#menu li a").css("padding", "1em 1.8em" );
//C. Target IE6 and below
if ($.browser.msie && $.browser.version <= 6 ) $("#menu li a").css("padding", "1em 1.8em" );
//D. Target Firefox 2 and above
if ($.browser.mozilla && $.browser.version >= "1.8" ) $("#menu li a").css("padding", "1em 1.8em" );
20. Scroll Effect to Obj
// Scroll Effect to Obj
var targetOffset = $(Obj).offset().top;
$('html,body').animate({scrollTop: targetOffset}, 1000);
// Appear Effect
$(Obj).animate({opacity: 'show', height: 'show'}, 1000);
// Appear Toggle Effect
$(Obj).siblings('*:last').children('.part').animate({opacity: 'toggle', height: 'toggle'}, 500);
// Message Effect
$(Obj)
.removeClass().addClass('message'+(type ? ' message_'+type : ''))
.html('Your Message').show().fadeOut(1000);
// Highlight Effect - Requires Color Plugin
function renderer_highlight ( Obj, color )
{
if ( color == null ) color = 'lightyellow';
var origColor = $(Obj).css('backgroundColor');
$(Obj).animate(
{ backgroundColor: color },
{ duration:300,
complete:function(){ $(this).animate({backgroundColor: origColor}, 300); }
}
);
}
// Remove all labels from #sample .actions that are not the first that are not the first
$('#sample .actions label:not(:first)').remove();
// Navigate the first .myText inside #myDiv
$('#myDiv .myText:first');
// or
$($('#myDiv .myText')[0]);
// or
$($('#myDiv').find('.myText')[0]);
// Check the last input that is not animated and is visible
$('#sample .actions label:visible:not(:animated):last input').attr('checked', 'checked');
21.
GridView with Select All CheckBox using JQuery
One of the handy features that one might with to put on GridView is the Select All checkbox which is similar to the one on Hotmail and Yahoo. You click the checkbox on the header and all items (checkboxes underneath) get checked.
I’ve seen several implementation for this feature long time ago. Myself wrote one. And all solutions were using some good amount of JavaScript. Today I was thinking, why not revisit the idea again, but this time using all mighty JQuery.
And as expected, the amount of code used to implement this simple feature is really small. I’m going to explore the JQuery code expecting you already know ASP.NET and how to use GridView along with SqlDataSource.

CheckBoxes are rendered on the last column. I’m mentioning last column because I’m going to use that on JQuery. Also it worth to mention that this GridView will render the header columns like this:
<tr>
<th align="left" scope="col">Category</th>
<th align="left" scope="col">Product</th>
<th align="right" scope="col">Unit Price</th>
<th align="left" scope="col">Supplier</th>
<th scope="col">
<input id="gvProducts_ctl01_chkSelectAll" type="checkbox" name="gvProducts$ctl01$chkSelectAll" />
</th>
</tr>
Notice the “th” tag; again because I’ll use this from JQuery. The rest of rows are rendered as normal “td” tags
As I am using AJAX Enabled Web Application, I have the option ASP.NET AJAX Client Events like onload event. I’m using this event to bind click event to each CheckBox on the GridView:
22. jQuery code to select text inside an input field on user click or focus:
$("#myInputField").focus(function(){
// Select input field contents
this.select();
});
// Add this behavior to all text fields
$("input[type=text]").focus(function(){
// Select field contents
this.select();
});
23. Get geographical location (geolocation) by IP address using jQuery
{
'status':'ok',
'IP': '74.125.45.100',
'CountryCode': 'US',
'CountryName': 'United States',
'RegionName': 'California',
'ZipPostalCode': '94043',
'City': 'Mountain View',
'Latitude': '37.4192',
'Longitude': '-122.057'
}
// In case of an error
{
'status':'parent server not responding'
}

RSS Feeds
Feed Comment 




Very nice article 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/