Register now or login here to start promoting your blog and your favourite articles.
Useful and Handy jQuery Tips and Tricks
25 Mar 2009 - 38 Comments
I have a list of jQuery tips and tricks for my development project. Now, I want to share it to everyone. In this article, I will assemble all the jQuery tips and tricks and cheat sheets that I got it online in a single page.
Author: kevin | Source: queness

When I start learning jQuery, I always look for a best way to implement a code. Or sometimes, look for the simplest solution among the rest, though it's not the elegant way to do it, but it's easy to understand. So, now, I'm gonna show you my favourite collection of jQuery tips and tricks

1. jQuery cheatsheets

First of all, it's good to have a cheatsheet as a reference. I found 3 of them online:

jQuery Cheatsheet from ColorCharge
jQuery Cheatsheet from ColorCharge WebBlog

jQuery Cheatsheet from Gscottolson WebBlog
jQuery Cheatsheet from Gscottolson WebBlog

jQuery Cheatsheet from From Far East WebBlog
jQuery Cheatsheet from From Far East WebBlog

2. 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
}); 

3. 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>

4. Make the entire LI clickable

This trick is very useful when you're using UL list to make a menu. What it does is, when you click on the LI area (outside of the link), it will search for the url in the anchor tag and execute the link:
	$("ul li").click(function(){
	  //get the url from href attribute and launch the url
	  window.location=$(this).find("a").attr("href"); return false;
	});
<ul>
	<li><a href="home">home</a></li>
	<li><a href="home">about</a></li>
	<li><a href="home">contact</a></li>
</ul>

5. 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>

6. 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;
});

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

8. 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>

9. Back to top button/link

A handy back to top button/link using jQuery with scroll to plugin. I like the scroll to top effect, you can test it by pressing the button below this page. You'll know what I meant : ) Get jQuery scrollTo plugin
$('#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

10. Columns of equal height

I think this script is quite useful. I haven't have a chance to use it yet. It's more on design. If you want columns have the same height, this function will answer your request. Inspired by CSSNewbie
$(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. Write our own selector

This is a more advance trick. I didnt know about this until I saw it from this website illuminatikarate.com.
//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>
<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>

12. Font resizing

This is one of the famous facilities on a webpage - able to let user increase the font size. I modified the script from shopdev.co.uk. Now, you'll be able to put in ID, Classes or HTML elements that you want the font to be adjustable into an array.
$(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>

MORE TIPS AND TRICKS ARE WANTED!

I will keep updating this post, so you can bookmark it. I hope this list will able to help you, I have modified some of the scripts to become more flexible. If you have some tips and tricks that you want to share with us. Please leave a comment. : ) Thanks!

Copyright & Usage

The effects and techniques demonstrated in tutorials on Queness can be used in whatever manner you wish without attribution. You cannot copy whole tutorials (unless permission is given), either in English or translated to another language.

Share This Post to Support Me! :)


Comments

wholesale gucci clothing on 2 Sep 2010 says:
<a href="http://www.gucci-buying.com">wholesale gucci clothing</a> provides you the best and cheapest bags. All the products at http://www.gucci-buying.com are 100% high

quality, competitive price, free shipping with best and timely service, 100% satisfaction. Big discount for big order. Welcome to make your choose.
Izrada Web Stranica on 1 Sep 2010 says:
THX from Bosnia!
cheapretailjordan on 31 Aug 2010 says:
[url=http://www.cheapretailjordan.com]cheap gucci clothing[/url]
[url=http://www.cheapretailjordan.com]Juicy Couture Bikini[/url]
[url=http://www.cheapretailjordan.com]Chanel t shirts[/url]
[url=http://www.cheapretailjordan.com]Christian Audigier Jeans[/url]
[url=http://www.cheapretailjordan.com]Polo t shirt[/url]
[url=http://www.cheapretailjordan.com]ed hardy handbags[/url]
[url=http://www.cheapretailjordan.com]armani jeans[/url]
[url=http://www.cheapretailjordan.com]Coogi Clothing[/url]
[url=http://www.cheapretailjordan.com]Radii ShoeS[/url]
[url=http://www.cheapretailjordan.com]cheap dolce gabbana shoes[/url]
web design on 12 Aug 2010 says:
Like these tricks mate, thanks alot.
prasanna on 19 Jun 2010 says:
cool tips ... thanks
SamsonDelila on 10 Jun 2010 says:
Most great works! Very very useful ...
Private Lessons on 26 May 2010 says:
Great Work! Thanks!
delicious on 9 May 2010 says:
I like the font resizing tip #12; but I noticed something. I don't think 1.2 is the inverse of 0.8. If you increase once and decrease once, you won't get back to the original size. If you use 1.25 and .8, then each will do the opposite of the other. Maybe it doesn't matter -- I'm OCD / anal that way. ;-)
kevin on 14 Oct 2009 says:
hi inderpreet, it put in the bottom of the page. please refer to my website, \"back to top\" button :)
Aaron McCall on 14 Oct 2009 says:
As an extension of tip # 10:

You could attach your height equalizer (setHeight) to the windows resize event, thus keeping the columns of equal height even if window width changes cause a change in content height. I have used a similar solution for just this purpose.


Leave a comment

Subscribe RSS Subscribe RSS, Keep yourself updated with queness latest posts!
Pixel Crayons

Buy wholesale computers directly from China at DHgate.com

Discover the tools to build your e-Commerce Site with Netfirms

Buy China Products from Made-in-China.com

Cocktail Dresses

SmartPhone Cell Phone

Wholesale electronics

Web Hosting Rating

Buy WOW Gold

Get your cdl today

Debt collector review

  •  
  •  
  •  
  •  
  •  

Community News

Recent Comments

Random Posts


View all posts and news Back to top

About the Author

A web designer and developer who is passionate and keen on contributing to the web development industry. Feel free to say hi to me, or follow me on twitter.

Kevin Liew