10 jQuery snippets for efficient developers

by Jean. 51 Comments -

jQuery is by far my favorite Javascript framework, which allows developers to create stunning visual effects, manipulate data properly, and much more. In this article, I have compiled 10 extremely useful jQuery snippets.

Load jQuery from Google

Google has a fresh version of jQuery, which is made available for developers. Instead of getting a jQuery copy, you should definitely take advantage of Google’s “generosity” and directly load their copy:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>

» Source

Validate a date of birth using jQuery

Validating dates of birth are a common task on websites that have content available only for users 18+ years old. Using jQuery, this is very easy to do, as shown in the following example:

$("#lda-form").submit(function(){
	var day = $("#day").val();
	var month = $("#month").val();
	var year = $("#year").val();
	var age = 18;
	var mydate = new Date();
	mydate.setFullYear(year, month-1, day);

	var currdate = new Date();
	currdate.setFullYear(currdate.getFullYear() - age);
	if ((currdate - mydate) < 0){
		alert("Sorry, only persons over the age of " + age + " may enter this site");
		return false;
	}
	return true;
});

» Source

Make sure an image has loaded properly

How do you know if an image has been properly loaded? In some particular cases such as a captcha, problems with the user experience may happen if an image hasn’t been loaded properly.
Using the simple piece of code below, you’ll be able to know if your image is displayed on the user screen.

$('#myImage').attr('src', 'image.jpg').load(function() {
    alert('Image Loaded');
});

» Source

XHTML 1.0 Strict valid target=”blank” attribute

The target=”blank” attribute can be useful when you want a link to be opened in a new tab or window. Though, the target=”blank” attribute is not valid XHTML 1.0 Strict.
using jQuery, you can achieve the same functionality without having validation problems.

$("a[@rel~='external']").click( function() {
    window.open( $(this).attr('href') );
    return false;
});

» Source

Search within text using jQuery

The following function will allow full text search on the page using jQuery. The feature is not only cool, but useful at the same time.

$.fn.egrep = function(pat) {
 var out = [];
 var textNodes = function(n) {
  if (n.nodeType == Node.TEXT_NODE) {
   var t = typeof pat == 'string' ?
    n.nodeValue.indexOf(pat) != -1 :
    pat.test(n.nodeValue);
   if (t) {
    out.push(n.parentNode);
   }
  }
  else {
   $.each(n.childNodes, function(a, b) {
    textNodes(b);
   });
  }
 };
 this.each(function() {
  textNodes(this);
 });
 return out;
};

» Source

“outerHTML” function

The well-known innerHTML property is very useful: It allows you to get the content of an HTML element. But what if you need the content, and also the HTML tags? You have to create an “outerHTML” function like this one:

jQuery.fn.outerHTML = function() {
    return $('
<div>').append( this.eq(0).clone() ).html();
};</div>

» Source

Clean way to open popup windows

Although their popularity decreased with the rise of popup blockers, pop-up windows can still be useful in some particular cases. Here is a nice snippet to open links in pop-up windows. Just add the popup css class to your link to make it work.

jQuery('a.popup').live('click', function(){
	newwindow=window.open($(this).attr('href'),'','height=200,width=150');
	if (window.focus) {newwindow.focus()}
	return false;
});

» Source

Quick and easy browser detection

Cross-browser issues are definitely the biggest problem a front-end web developer has to face at work. Thanks to jQuery, detecting browsers have never been so easy, as shown below:

//A. Target Safari
if( $.browser.safari ) $("#menu li a").css("padding", "1em 1.2em" );

//B. Target anything above IE6
if ($.browser.msie && $.browser.version > 6 ) $("#menu li a").css("padding", "1em 1.8em" );

//C. Target IE6 and below
if ($.browser.msie && $.browser.version <= 6 ) $("#menu li a").css("padding", "1em 1.8em" );

//D. Target Firefox 2 and above
if ($.browser.mozilla && $.browser.version >= "1.8" ) $("#menu li a").css("padding", "1em 1.8em" );

» Source

Get relative mouse position

Do you ever want to be able to get the relative mouse position? This very handy function will return the mouse position (x and y) according to its parent element.

function rPosition(elementID, mouseX, mouseY) {
  var offset = $('#'+elementID).offset();
  var x = mouseX - offset.left;
  var y = mouseY - offset.top;

  return {'x': x, 'y': y};
}

» Source

Parse an xml file using jQuery

XML files are very important on the Internet, and any developer has to parse them from time to time. Thanks to jQuery and all its powerful functions, the whole process is painless, as demonstrated in the example code below:

function parseXml(xml) {
  //find every Tutorial and print the author
  $(xml).find("Tutorial").each(function()
  {
    $("#output").append($(this).attr("author") + "
"); }); }

» Source

  • Peter

    re : JQuery from Google
    Why not adjust JQuery’s version number in the snippet ( if only for the copy & paste crowd )

  • http://ruakbar.deviantart.com Abdul Akbar

    Hi,

    As a design/developer I really love this post. Several useful things to learning.

    Keep it up!

  • Pingback: 10 jQuery snippets for efficient developers | Lively Web Tuts

  • Liam

    to support jQuery 1.3+

    this:

    $(“a[@rel~='external']“).click( function() {
    window.open( $(this).attr(‘href’) );
    return false;
    });

    should be

    $(“a[rel~='external']“).click( function() {
    window.open( $(this).attr(‘href’) );
    return false;
    });

    There is no need for the @ character after jQuery 1.2.6

  • http://ineeddiscipline.com Dean Saliba

    I’m learning this sort of stuff and am looking forwarding trying it out. :)

  • Pingback: 10 jQuery snippets for efficient developers | Webs Developer

  • http://www.w3spice.com waqas

    nice snippets…..looking forward for more

  • adam j. sontag

    To reliably bind a load callback to an image, you need to bind the load handler BEFORE changing the source attribute.

    $(“img”).load(fn).attr(“src”,newsrc);

    Also, as of jQuery 1.3, @ in attribute selectors is deprecated and will break code.

  • http://www.tekoestudio.com Teko

    Nice snippets thanks for share!!

    Teko

  • http://jamie3d.com Jamie

    Nice group of snippets! I especially like the image loaded one. I didn’t know that could be detected.

  • http://www.skirting-and-bellows.com Grant

    very nice snippets. Would have saved me hours of work if I had found this sooner.

  • Jgarcia

    You should not be using jQuery browser sniffing functions. They recommend you to use feature detection instead by using http://docs.jquery.com/Utilities/jQuery.support
    or creating your own if not available.

  • Pingback: 10 jQuery snippets for efficient developers | TopRoundups

  • Pingback: links for 2009-12-14 | Digital Rehab

  • http://www.designstudio16.com saurabh shah

    nice snippets ! looking forward for more . ..

  • dietbrisk

    as a jquery programmer, i have to say, i have never found the need to use any of these snipplets.

  • http://ramaboo.com David Singer

    You might want to change http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js to
    http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js or http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js so that you get automatic updates.

  • http://blog.mrhenry.be Yves Van Broekhoven

    Nice list!

  • Joshua M

    Your rel link is not that great…

    Doing window.open() allows for popup blockers to step in… the best solution i’ve come across is simply use .attr() to set the target to blank – then return true. It allows the browser to address the link like it was a normal blank targeted link,

  • http://coda.co.za coda

    Simpler way to open links in a new window without the target attribute in the markup, attached it via jQuery:

    $(”a[rel~='external']“).attr(‘target’, ‘_blank’);

  • Pingback: ChrisLove at 12/15/09 01:53:17 | Exectweets

  • http://www.jannis-gerlinger.de Jannis Gerlinger

    Thats what i need. Thank you !

  • Joshua Briley

    This is great. I was looking for a Jquery “Pop-Up” Window thing about two weeks ago. This is now preserved. ;-) Also, I’ve had similar success with the “target=”_blank” using this little snippet: $(“a[href^=http]“).attr(“target”, “_blank”);

  • http://www.vincent-therry.com Vincent Therry

    Great resources, really useful ! Thank you for thoses snippets

  • Richard Pöttler

    Could you point out, or give me a link, which explains, why I should use jQuery from google?

  • Pingback: Links for the day | CssGalleries

  • Jeremy

    @Richard Pittler

    The concept is called a content delivery network. The primary benefit is that a user who has visited another site that uses the same CDN will not have to load the external resource again. Instead the resource will be pulled from the user’s cache thereby making your page load faster. More detail:

    en.wikipedia.org/wiki/Content_delivery_network

  • Julian Nicholls

    Using jQuery.browser (partiularly jQuery.browser.version) is deprecated. You should always use feature detection via jquery.support: http://docs.jquery.com/Utilities/jQuery.support

  • Pingback: 10 jQuery snippets for efficient developers | Ids & Classes

  • http://www.dotnetspark.com Pankaj

    Nice Article thanks for sharing …Waiting for more number of snippets..

  • http://www.thehappypixel.com Bob Duncan

    I think that it is a bad idea to post some of these ideas. Some rules were not made to be broken and this opens up the gate for people that don’t know better (e.g. target, popup, browser sniffing). Otherwise, there is some nice stuff here.

  • James

    Some constructive feedback…

    You could have made this a much better post if you’d chosen instead to focus the entire article on point number 1.

    I find that your posts often have the ‘more is better’ mentality – why feature 10 little tricks of lower quality, with little or no information about each, when you could instead choose the one or two that people will actually USE, and go into great detail about those?

    Cheers

  • http://ranacseruet.blogspot.com/2009/12/jquery-xml.html rana

    Nice tips. I have also written on the last topics, for the beginners, parsing xml data using jquery.

  • http://www.web-design-talk.co.uk Rob

    Great post. Liked the date validation code especially.

  • http://www.trendpointe.com tommy

    nice tips, your blog is amazing. i will bookmark it and share it to my friends

  • http://www.phonello.com/ Antony

    Nice, thanks for sharing. I believe this will be usefull.

  • http://www.haushalt-wohnen.de Hannelore

    “Get relative mouse position” This is a good one. I had always trouble with my mouse before using this.

  • http://www.blogpostideas.com Codrut @ Blog Post Ideas

    I am brand new to jQuery snippets, but your article started with a bang, explaining what that is. Most bloggers would simply suspect everybody would know what that means, and would simply start their post with the “advanced” stuff.

  • http://www.laranevans.com/ Laran Evans

    I love posts like this. Very handy to have snips like this on hand. Hey, that was a pun!

  • http://www.charlotterage.com Charlotte

    Great snippets. I’ll be using a few of these for sure.

  • Bill AHern

    I don’t understand why jquery deprecated the browser detection function and point people to the jquery.support – if what I need to do is specifically detect a browser, I haven’t seen anything in the support function that allows me to easily accomplish that task, *particularly* when I want to write a small bit of code simply to correct any wonky =< IE6 behavior.

  • http://decipherdigital.com Jon

    I’ve used the load function before but had completely forgotten about it; you’ve just solved a problem I’ve been puzzling over for days. Cheers!

  • eVias

    Hey,
    use of $.browser is deprecated, as jQuery says on the website.

    I think we should not be testing on the BROWSER, but on the FEATURES. What I mean by that is we should be testing on enabled features and execute the code given to that result .

    Executing a certain kind of code for a certain kind of browser is deprecated in the way that browsers are always going to evoluate, and in 10 years, I still wan’t my code to function .

    Still I really think it is a good article :]

  • Pingback: Jquery Link Compilation | CssGalleries

  • Pingback: links for 2009-12-28 « 2LeggedSpider

  • http://blog.seanja.com SeanJA

    Cool, thanks for the mention… I was wondering why the analytics graph looked a little off.

    My understanding of window.open is that it will work as long as it is fired by the user’s mouse click rather than automatically.

    As for target=_blank…. well, that is deprecated, and can be overridden in certain browsers making your site not work the way that you would expect it to.

  • http://ghosts-it.com radz nguyen

    Could you point out, or give me a link, which explains, why I should use jQuery from google?

  • http://blog.seanja.com SeanJA

    @radz_nguyen Here you go:

    http://stackoverflow.com/questions/1014203/best-way-to-use-googles-hosted-jquery-but-fall-back-to-my-hosted-library-on-goo

  • http://jessywu.net/ Jessy Wu

    nice set of snippets here. definitely a lot to learn. thanks for sharing, Jean.

  • http://www.spinthebottle.ru STB

    Oh, thanks for this snippets. Some of them is really necessary.

  • Pingback: designfolio: