Saturday, May 22, 2010

Top 10 jQuery Snippets (including jquery 1.4)

images

Amazing collection of the top 10 most used jQuery snippets that you need to know about! Includes new amazing 1.4 jQuery framework methods.

I have found that people are going bananas over jQuery, so i’ve decided to share my top 10 jQuery snippets that i KNOW you will need to use at one point or another.

Amazing collection of the top 10 most used jQuery snippets that you need to know about! Includes new amazing 1.4 jQuery framework methods.

I have found that people are going bananas over jQuery, so i’ve decided to share my top 10 jQuery snippets that i KNOW you will need to use at one point or another. So here they are, enjoy! I have also added jquery 1.4 features never used before.

1. The quick copy paste jQuery starter embed

Almost every time I start using jQuery I need to paste this in to start writing my beautiful code.

<script src="http://code.jquery.com/jquery-latest.js"></script>  
<script>  
$(document).ready(function(){  
// jQuery Code Here  
});  
</script> 


You can either paste this in your header (if you are using jquery for any appearance changes its suggested to do so in the header) or you can add it at the end of your body, that way your styles will load first (hence making a faster load) and then the jquery will be loaded last.



2. Value swap (usually for search fields)



I find myself using this rather often, whenever you have a search field and you want it to defaultly display a value “search…” and have that value empty out on focus, well this is how to do this with jQuery 1.4.



swap_val = [];  
$(".swap").each(function(i){  
swap_val[i] = $(this).val();  
$(this).focusin(function(){  
if ($(this).val() == swap_val[i]) {  
$(this).val("");  
}  
}).focusout(function(){  
if ($.trim($(this).val()) == "") {  
$(this).val(swap_val[i]);  
}  
});  
});  


This jquery will create an array with every input field that has the class swap. For example:


<input type="text" class="swap" value="Swap Me!" /> 


The value Swap Me! will be erased when you click in the input field, and it will come back in if you don’t enter anything.



3. Equal Column Height



Unfortunately css does not support this natively, sometimes when creating column based layouts it looks so much better if the columns aligned by height, so here is the easy way of doing this.



var max_height = 0;  
$("div.col").each(function(){  
if ($(this).height() > max_height) { max_height = $(this).height(); }  
});  
$("div.col").height(max_height);  


This will go through every div with class col and check for which one contains the highest size, once done it will apply that height to all divs with class col. For example:



<div style="height:200px;" class="col">
</div>
<!-- this being the higher div will be set as the max_height -->  
<div class="col">
</div>
<!-- this being the smaller div will be made 200px high -->  


If you read the comments above you will see that each div has the class col, and that the second div will be set at height 200px.



4. On Hover add and Remove a class



Let’s say you want to have a suckerfish dropdown, or maybe you just want to add a cool hover on a div, well in some browsers thats not allowed to be done with pure css, hence use this simple technique and you will have cross browser hover with any two class you want.



 



$('.onhover').hover(  
function(){ $(this).addClass('hover_style_class') },  
function(){ $(this).removeClass('hover_style_class') }  
)  


The code above will apply a class home_style_class on hover of an element with the class onhover.



5. Live Event Binding



With jquery you can capture an onclick event with the .click() method, but this is the slower less efficient way. Also if you created new elements with ajax or with jquery those new elements will not be bound by the regular click() method. So using live click/submit and so on will apply itself to all new elements, and will only bind once to all.



$(".element").live("click", function(){  
// do something on click  
});


The code above will apply any code you want on click event on an element with class element.



6. Partial Page Refresh



Okay personally when the term ajax comes to mind i get a little worried… but I found this amazing technique to refresh page content without any real ajax or special tricks. All you need is to apply an id to a certain element, and run this little script, choose how many seconds to wait until refresh and VUALA!



setInterval(function() {  
$("#refresh").load(location.href+" #refresh>*","");  
}, 10000); // seconds to wait, miliseconds  


Okay so the script above will refresh the div with id refresh every 10 seconds… this can be so awesome in so many cases! Btw make sure you have tags inside the refresh div, otherwise it doesn’t seem to work with pure text.



7. Each Element



I seem to use this pretty often when i want to do something with a set of elements, for example if you do your own form validation and you want to check each input field before submitting.



$("input").each(function (i) {  
//do something with each and pass i as the number of the element  
}); 


So choose an element to cycle through, it can be a set of li’s in a chosen unordered list, or all the input fields as above. Use the i to get the number of the current element, and of course the $(this) to do something to the element it’s going through.



8. Find an element close by (jQuery 1.4)



With the new jQuery 1.4 we have the new awesome feature of the closest() method which will find the element closes to the current one. So no more searching through the parents and children to get to the close element we need.



$("li").click(function(){  
$(this).closest(".me").addClass("smile");  
}); 


The code above will find the closes class me to the li that was clicked on and add class smile to it. Hence you can see how beneficial this can be!



9. Delay animation/effect



Another great new feature of the 1.4 jquery framework is the Delay method which allows you to delay an animation. Instead of using the setTimeout method, you can now simply add the .delay() method and pass in how long to delay, like this:



$(".alert").delay(2000).fadeOut();  


The above will fade out an element with class alert after 2 seconds. This can be used for growl like notifications.



10. Check if an element contains a certain class or element



Another awesome feature of jQuery 1.4 that will be quite handy is the has method. This method will find if a an element contains a certain other element class or whatever it is you are looking for and do anything you want to them.



$("input").has(".email").addClass("email_icon");  


In the above code we will look through all inputs that have the class email and add the class email_icon.



Here are some that didn’t make the top 10 cut:



Creating the zebra stripe effect on UL/OL or Tables



Sometimes we have tables or ordered/unordered lists that we want to be easily read. Here is a quick jq trick:



$("tr:odd").addClass("odd");  
$("li:odd").addClass("odd");  


The code will add the class odd to every other element!



Automatic external link open in New Window



Tired of having to add target=”_blank” every time you don’t want your visitors to navigate away from your page? Let jquery do the work!



$('a').each(function() {  
var a = new RegExp('/' + [removed].host + '/');  
if(!a.test(this.href)) {  
$(this).click(function(event) {  
event.preventDefault();  
event.stopPropagation();  
window.open(this.href, '_blank');  
});  
}  
}); 


Now every a href in your page will open in a new window if it doesnt go somewhere in your own website!



Thanks for checking out my little list of snippets, if you have any suggestions or corrections comment below and i will try to add them for further reference!


People who read this post also read :



If you liked my post then,

Subscribe to this site via Email:

Click here to Subscribe to FREE email updates from "itrickz", so that you do not miss out anything that can be valuable to you and your blog!!

DropJack!
Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

1 comments: on "Top 10 jQuery Snippets (including jquery 1.4)"

Harishankaran said...

Excellent collection.. After a long time, seeing a neat post on jquery which has something new..

Post a Comment