18

th

Jan

Top 10 jQuery Snippets (including jquery 1.4)

Top 10 jQuery Snippets (including jquery 1.4)

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! Thanks to the following for the inspiration and code: css-tricks  reindel nettuts

Related Articles

Comments

By SMiGL on Wed - Jan 20th, 2010

>Value swap
You can replace focusin, focusout events bind ( “focus”, function), bind ( “blur”, function), respectively, if you use jQuery 1.3.2

By ms on Wed - Jan 20th, 2010

For the value swap you could like to use the “defaultValue” JavaScript attribute.

By Anoop D on Wed - Jan 20th, 2010

Being a regular for the latest in web development i can assure this is one of the best snippets i have found ever ... Great work continue man ..smile

By K. Adam Christensen on Wed - Jan 20th, 2010

Thanks for the snippets.

One thing I would like to point out is that you should cache some of your selectors and values.

For instance, in your equal height example, you should probably cache the value of height() as well as $(“div.col”).

[removed][removed]

If you’re more daring and like to make the JS work:
[removed][removed]

Lastly, on your example for doing zebra stripes, you can combine the selectors into one with
[removed][removed]

By K. Adam Christensen on Wed - Jan 20th, 2010

Sorry about that last post, the code examples can be found at http://gist.github.com/282471

By agrublev on Wed - Jan 20th, 2010

Hey Anoop D, thanks man smile out all the people who had to bullet proof my working snippets you just made my night smile i write this articles to help people start or continue with web development as i did once! So it’s REALLY nice to hear those nice words and to motivate me to write more articles that i hope to help the community!

By Anonymous Coward on Sat - Jan 23rd, 2010

For number 1 you should be pasting
http://code.jquery.com/jquery-latest.min.js
instead of
http://code.jquery.com/jquery-latest.js
This will result in a smaller download for your viewers.

By Maicon Sobczak on Sat - Jan 23rd, 2010

Useful snippets!


To open external links in a new window I use:

$(“a[href^=http://]”).attr(“target”,“_blank”);

By Andrée Hansson on Sat - Jan 23rd, 2010

If you’re doing a list of jQuery snippets, and including 1.4, you should at least give examples on differences in 1.3.2 and 1.4.

.closest(expr) is available in 1.3.2 too, for example.

In jQuery 1.4, the .hover method can take only one function, which will be bound on both mouseenter and mouseleave.

And .delay can also take the ‘slow’, ‘fast’ arguments as well, it will hopefully be added to the API docs in a not-too-far future.

By Charly on Sun - Jan 24th, 2010

Great list.
I think jquery is easy to understand and always faster to develop.

By Sneakyness on Sun - Jan 24th, 2010

THESE BLOW! How dare you even call this jQuery!

By Sneakyness on Sun - Jan 24th, 2010

YOUR COMMENTS ARE BROKEN! THAT’S HOW GOOD YOU ARE BUDDY!

By Paul.irish on Sun - Jan 24th, 2010

Thanks for helpful JQuery tips!

By jboesch on Sun - Jan 24th, 2010

WTF is a jquerie

By coldhead on Sun - Jan 24th, 2010

This is the greatest showcase of jQuery’s features that I have ever seen. Reading your snippets reminds me of reading Nabokov: my head and my heart ache to realise I will never match your lucid, potent, powerful writing. You have an extraordinary appreciation of jQuery’s usefulness, and the best methods of deploying it. This is certainly not just another lame attempt to cash in on the current buzz around jQuery. No, this is truly a post for the ages. I will be telling my grand children about this post, and I will certainly be subscribing to your blog. We are forever in your debt, and your shadow. Thank you so much.

By trix on Mon - Jan 25th, 2010

Guys, if this blog isn’t up to your standards maybe you should stick to your webring…

By Sneakyness on Mon - Jan 25th, 2010

Or we could tell him it sucks and encourage him to write real content?

By Angel Grablev on Mon - Jan 25th, 2010

Okay i want to quickly reply to you comments as it seems my blog is not up to your standards as trix said.

@sneakyness the comments seem to work just fine, since ur using them

@coldhead i had fun reading your comment, i appreciate your sarcasm. although it does pain me to hear that my blog was not helpful to you, i have otherwise heard quite a few people tell me they learned something new… my whole purpose for this blog has always been, and will be, to help people learn something new as i do every day. if that does not satisfy you i would gladly never want you to read my articles again as they are not up to your par.

@sneakyness yes buddy it is easy to point fingers at others and tell them what they do sucks, I do not believe you are the owner of a blog that writes about anything… hence your opinion does not really matter to me. I do what i love, and i love what i do smile hence please keep your snotty comments to your self please

@jboesch no idea what you are referring to

By Robbert on Fri - Jan 29th, 2010

Just a quick tip: You can easily create equal columns by using faux columns. A List Apart has a nice article about it.

http://www.alistapart.com/articles/fauxcolumns/

I’ve done it a couple of times and still happy about that design choice.

This way you are able to add content to the column without calling your function to resize the column.

Wrapping divs around it will support multiple of those things on your page with or without tops and bottoms wink Good luck!

Robbert

By KathyCARROLL23 on Thu - Mar 04th, 2010

Various people in all countries get the loans in different creditors, just because this is comfortable and fast.

By MurielBurns22 on Wed - Mar 10th, 2010

I could dispute a lot just about the history of term paper writing, but I would recognize that the purchase term paper service could write the high quality custom essays always. Is this correct?

Have something to share?

Remember my personal information

Notify me of follow-up comments?

Please enter the word you see in the image below: