10 awesome jQuery snippets

by Jean. 23 Comments -

jQuery gave a new life to JavaScript coding. Thanks to this great tool, it is now possible to build powerful and responsive web pages. In this article, I have compiled 10 jQuery snippets that will definitely help you in your daily client-side coding.

Preloading images

Preloading images is useful: Instead of loading an image when the user request it, we preload them in the background so they are ready to be displayed. Doing so in jQuery is very simple, as shown below:

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }

jQuery.preLoadImages("image1.gif", "/path/to/image2.png");

→ Source: http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript

target=”blank” links

The following snippet will open all links with the rel="external" attribute in a new tab/window. The code can be easily customized to only open links with a specific class.

$('a[@rel$='external']').click(function(){
     this.target = "_blank";
});

/* 
   Usage:
   <a href="http://www.catswhocode.com" rel="external">catswhocode.com</a>
*/

→ Source: http://snipplr.com/view/315/-jquery–target-blank-links/

Add a class to the <body> tag if JavaScript is enabled

This snippet is just a line of code, but it is one of the easiest way to detect if JavaScript is enabled on the client browser. If yes, a hasJS class will be added to the <body> tag.

$('body').addClass('hasJS');

→ Source: http://eisabainyo.net/weblog/2010/09/01/10-useful-jquery-snippets/

Smooth scrolling to an anchor

jQuery is known for its ability to let developers easily create stunning visual effects. A simple, but nice effect is smooth sliding to an anchor. The following snippet will create a smooth sliding effect when a link with the topLink class is clicked.

$(document).ready(function() {
	$("a.topLink").click(function() {
		$("html, body").animate({
			scrollTop: $($(this).attr("href")).offset().top + "px"
		}, {
			duration: 500,
			easing: "swing"
		});
		return false;
	});
});

→ Source: http://snipplr.com/view.php?codeview&id=26739

Fade in/out on hover

Another very cool effect – which is very popular among clients – is indeed the fade in/fade out on mouseover. The code below set opacity to 100% on hover, and to 60% on mouseout.

$(document).ready(function(){
    $(".thumbs img").fadeTo("slow", 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads

    $(".thumbs img").hover(function(){
        $(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover
    },function(){
        $(this).fadeTo("slow", 0.6); // This should set the opacity back to 60% on mouseout
    });
});

→ Source: http://snipplr.com/view/18606/

Equal column height

When building a column based website, you often want that all columns have the same height, as displayed in a good old table. This snippet calculate the height of the higher column and automatically adjust all other columns to this height.

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

→ Source: http://web.enavu.com/tutorials/top-10-jquery-snippets-including-jquery-1-4/

Enable HTML5 markup on older browsers

HTML5 is definitely the future of client-side web development. Unfortunely, some old browsers do not even recognize new tags such as header or section. This code will force old browsers to recognize the new tags introduced by HTML5.

(function(){if(!/*@cc_on!@*/0)return;var e = "abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video".split(','),i=e.length;while(i--){document.createElement(e[i])}})()

A better solution is to link the .js file to the <head> part of your HTML page:

<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

→ Source: http://remysharp.com/2009/01/07/html5-enabling-script/

Test if the browser supports a specific CSS3 property

Here is a simple jQuery function to check if the client browser supports a specific CSS3 property. In this example, border-radius is the property we want to check, but of course this can be modified easily.

Note that when passing the property, you have to omit the dash to prevent syntax error. So instead of border-radius, you have to pass “borderRadius” or “BorderRadius”.

var supports = (function() {
   var div = document.createElement('div'),
      vendors = 'Khtml Ms O Moz Webkit'.split(' '),
      len = vendors.length;

   return function(prop) {
      if ( prop in div.style ) return true;

      prop = prop.replace(/^[a-z]/, function(val) {
         return val.toUpperCase();
      });

      while(len--) {
         if ( vendors[len] + prop in div.style ) {
            // browser supports box-shadow. Do what you need.
            // Or use a bang (!) to test if the browser doesn't.
            return true;
         } 
      }
      return false;
   };
})();

if ( supports('textShadow') ) {
   document.documentElement.className += ' textShadow';

→ Source: http://snipplr.com/view/44079

Get url parameters

Getting url parameters is pretty easy using jQuery. The following snippet will do the job!

$.urlParam = function(name){
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (!results) { return 0; }
	return results[1] || 0;
}

→ Source: http://snipplr.com/view/26662

Disable the “Enter” key in forms

By default, a form can be submitted by pressing the “Enter” key. Thought, on some form, this keyboard shortcut can cause problems. Here is how you can prevent unwanted form submission by disabling the “Enter” key with jQuery.

$("#form").keypress(function(e) {
  if (e.which == 13) {
    return false;
  }
});

→ Source: http://snipplr.com/view/10943/disable-enter-via-jquery/

  • http://marttilaine.com Martti Laine

    About the fading images, see this post: http://scriptish.com/2011/10/09/stop-queueing-animations-in-jquery/

    Hopefully this isn’t too much self-promotion as it has a point =)

    • http://www.wsd.co.il mazi

      Thanks Matti, Fading images can be changed to fading texts, creating a nice “news area” that withdraw the visitors to read.

    • Xander

      It is self-promoting and it is nice to see somebody who uses some sort of event garbage collection while animating.

  • http://www.webverwalter.com Thomas

    thank you, very helpful.

  • http://united1in.com Vikram

    Good collection, some of them are new concepts to me, i would love to see an article on how to create custom jquery plugins.
    Thanks for the article

    • http://www.wprecipes.com Jean-Baptiste Jung

      That’s a great idea! I keep it in mind for a future article.

    • http://www.purplematter.com M.B.

      Smashing Magazine published an intersting article about jQuery Plugin Patterns: http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/

  • http://scottelkin.com Scott Elkin

    Dude! These are awesome!

  • Wendelle

    Thanks! this could be a great help for me! cheers!

  • http://www.choosedaily.com Vernon Kesner

    These are great, although I’m wondering if the last one needs to include a “this might piss users off” warning.

  • http://www.szek.net andi

    thank you! some of the snippets are very useful.
    especially the “Disable Enter Key in Forms” and “Smooth Scroll to Top”.

    regards,
    andi

  • http://royspages.co.uk Roy Smith

    Nice list of tips. Very useful. Thanks

  • http://howtojailbreakiphone4s.org/ Mike

    jQuery is great peace of technology but currently I am just learning how to get out the full potential.

    Thanks for sharing these snippets will find a good use for picture preloader snippet

  • http://mmovz.com/ Daniel

    Jean, would you say that preloading images slows down your website or speeds it up? I’m really not a friend of using too many jQuery and JavaScript files, as I really feel like they are slowing down my website drastically.

    • http://www.wprecipes.com Jean-Baptiste Jung

      Preloading images won’t make your website faster, but the visitor will feel that the website is fast because when he’ll request an image, he’ll see it without loading time, as the picture have already been loaded in the background.

      But of course, if you preload too many image, it will make your website slower, so you should not abuse of this technique ;)

      • bart

        Can’t you preload after page load? This would not affect the rendering speed of the current page at all.

  • http://www.mcpdesigns.net MCPDesigns

    The enter key needs much more checking (for IE & other purposes than e.which == 13. I’ve always done this:

    $(“#form”).keypress(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code === 13) { // Enter keycode
    if (e.preventDefault) { e.preventDefault(); }
    else { e.returnValue = false; }

    return false;
    }
    });

    That way you have all grounds covered.

  • Doudou

    Coucou Loulou !
    Tu es un beau félin dis-moi !
    groaaaaaaaaaaaaaar !
    miaouuuuuuuuuuu

  • http://corymathews.com CoryMathews

    In regards to the target=blank topic.

    While that way technically works, why would you want to add the rel= to each link that is external? I wrote a plugin recently that handles it for you. by checking the domain vs the domain in the link.

    $(this).find("a[href^='http:']").not("[href*='" + document.location.host + "']");

    http://corymathews.com/jquery-external-image-and-tab-plugin/

  • http://www.dinovici.com Vic Dinovici

    Thanks for this! Great collection of jQ snippets! Started using the target=”_blank” one; for some reason sometimes the html one is just not open a new tab, especially when is for emails (mailto).

  • http://www.psd-dude.com John

    Useful stuff, thank you!

  • http://thewebdesignbay.com Gustavs Jurisons

    Very nice snippets indeed. However, I personally think that preloader and hover effects both look awesome but sometimes just terrible on very slow computers.
    But it’s just mine opinion :)

  • Arvind Bhateja

    Thanks for the scripts. :)

    Just found one bug in the CSS3 support snippet.

    The len variable should be defined inside the inner (anonymous) function because after calling it for a few times it will be less than 0 and while loop will be running infinitely.