// detect if element exists if($('.yourElement').length > 0){ //Do stuff with your element } 10 awesome jQuery snippets Published on November 21st, 2011 by Jean-Baptiste Jung. 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: catswhocode.com */ → Source: http://snipplr.com/view/315/-jquery–target-blank-links/ Add a class to the 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 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 part of your HTML page: → 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'; $.getJSON() The easiest way to load some JSON data in jQuery is with the $.getJSON() function and using the callback to do something with the data. If the URL to get the JSON data is at /json/somedata.json then it can be retrieved and something done with it like so: 1 $.getJSON('/json/somedata.json', function(data) { 2 // do something with the data here 3 }); $.ajax() The above is a shortcut to the $.ajax() method. If you needed to set some of the other AJAX properties use the $.ajax() function instead. The following is the equivilent of the above: 1 $.ajax({ 2 dataType: 'json', 3 success: function(data) { 4 // do something 5 }, 6 url: '/json/somedata.json' 7 }); $.parseJSON(); Finally, a JSON encoded string can be converted to a Javascript array using $.parseJSON(). If "string" in the example below contains a JSON string it can be converted to an array like so: 1 data = $.parseJSON(string); The string could potentially be retrived using AJAX from the server as plain text, and then converted to an array like this, although normally you would use the dataType 'json' and leave it up to jQuery to do it for you: view sourceprint? 1 $.ajax({ 2 dataType: 'text', 3 success: function(string) { 4 data = $.parseJSON(string); 5 // do something 6 }, 7 url: '/json/somedata.json' 8 }); Run JavaScript Only After Entire Page Has Loaded Last updated on: OCTOBER 2, 2010 $(window).bind("load", function() { // code here }); json jquery error catching $.get('/path/to/url', function (data) { if( !data || data === ""){ // error return; } var json; try { json = jQuery.parseJSON(data); } catch (e) { // error return; } // use json here }, "text");