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

 

41 Comments

  1. Peter
    Posted December 14, 2009 at 6:43 pm | Permalink

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

  2. Posted December 14, 2009 at 6:58 pm | Permalink

    Hi,

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

    Keep it up!

  3. Liam
    Posted December 14, 2009 at 7:27 pm | Permalink

    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

  4. Posted December 14, 2009 at 7:50 pm | Permalink

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

  5. Posted December 14, 2009 at 9:00 pm | Permalink

    nice snippets…..looking forward for more

  6. adam j. sontag
    Posted December 14, 2009 at 9:02 pm | Permalink

    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.

  7. Posted December 14, 2009 at 9:23 pm | Permalink

    Nice snippets thanks for share!!

    Teko

  8. Posted December 14, 2009 at 10:02 pm | Permalink

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

  9. Posted December 14, 2009 at 10:51 pm | Permalink

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

  10. Jgarcia
    Posted December 15, 2009 at 12:37 am | Permalink

    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.

  11. Posted December 15, 2009 at 7:32 am | Permalink

    nice snippets ! looking forward for more . ..

  12. dietbrisk
    Posted December 15, 2009 at 8:32 am | Permalink

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

  13. Posted December 15, 2009 at 11:51 am | Permalink
  14. Posted December 15, 2009 at 12:17 pm | Permalink

    Nice list!

  15. Joshua M
    Posted December 15, 2009 at 3:45 pm | Permalink

    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,

  16. Posted December 15, 2009 at 3:52 pm | Permalink

    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’);

  17. Posted December 15, 2009 at 4:37 pm | Permalink

    Thats what i need. Thank you !

  18. Joshua Briley
    Posted December 15, 2009 at 5:41 pm | Permalink

    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”);

  19. Posted December 15, 2009 at 5:41 pm | Permalink

    Great resources, really useful ! Thank you for thoses snippets

  20. Richard Pöttler
    Posted December 15, 2009 at 5:49 pm | Permalink

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

  21. Jeremy
    Posted December 15, 2009 at 7:41 pm | Permalink

    @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

  22. Julian Nicholls
    Posted December 15, 2009 at 9:19 pm | Permalink

    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

  23. Posted December 16, 2009 at 1:09 am | Permalink

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

  24. Posted December 16, 2009 at 5:06 am | Permalink

    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.

  25. James
    Posted December 17, 2009 at 1:50 am | Permalink

    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

  26. Posted December 17, 2009 at 9:09 am | Permalink

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

  27. Posted December 17, 2009 at 4:05 pm | Permalink

    Great post. Liked the date validation code especially.

  28. Posted December 17, 2009 at 10:33 pm | Permalink

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

  29. Posted December 18, 2009 at 8:32 pm | Permalink

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

  30. Posted December 18, 2009 at 11:47 pm | Permalink

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

  31. Posted December 19, 2009 at 10:02 pm | Permalink

    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.

  32. Posted December 21, 2009 at 5:32 pm | Permalink

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

  33. Posted December 21, 2009 at 5:41 pm | Permalink

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

  34. Bill AHern
    Posted December 21, 2009 at 7:06 pm | Permalink

    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.

  35. Posted December 22, 2009 at 10:17 pm | Permalink

    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!

  36. eVias
    Posted December 23, 2009 at 10:30 am | Permalink

    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 :]

  37. Posted December 30, 2009 at 3:59 am | Permalink

    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.

  38. Posted January 1, 2010 at 6:52 am | Permalink

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

  39. Posted January 1, 2010 at 4:43 pm | Permalink
  40. Posted January 23, 2010 at 1:12 pm | Permalink

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

  41. Posted February 22, 2010 at 11:52 am | Permalink

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

10 Trackbacks

  1. [...] Direct Link [...]

  2. [...] 10 jQuery snippets for efficient developers Share and Enjoy: [...]

  3. [...] 10 jQuery snippets for efficient developers Submitted by Nirhana [...]

  4. By links for 2009-12-14 | Digital Rehab on December 15, 2009 at 2:36 am

    [...] 10 jQuery snippets for efficient developers (tags: jquery snippets code javascript) [...]

  5. By ChrisLove at 12/15/09 01:53:17 | Exectweets on December 15, 2009 at 4:00 pm

    [...] Pro Tweets 10 jQuery snippets for efficient developers http://www.catswhocode.com/blog/10-jquery-snippets-for-efficient-developers ChrisLove – Tue 15 Dec 13:53 0 [...]

  6. By Links for the day | CssGalleries on December 15, 2009 at 6:59 pm

    [...] 10 jQuery snippets for efficient developers [...]

  7. [...] via CatsWhoCode.com [...]

  8. By Jquery Link Compilation | CssGalleries on December 23, 2009 at 10:37 pm

    [...] 10 jQuery snippets for efficient developers [...]

  9. By links for 2009-12-28 « 2LeggedSpider on December 28, 2009 at 2:03 pm

    [...] 10 jQuery snippets for efficient developers (tags: jquery, tips) [...]

  10. By designfolio: on February 27, 2010 at 10:01 pm

    [...] fonte: cats who code Published on jan 20, 2010 Filed under: Artigos, Jquery | No Comments 101 portfolios incriveis Sites inspiradores – Verde [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe without commenting

  • Smashing Network
WordPress Appliance - Powered by TurnKey Linux