10 jQuery snippets for efficient developers

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>

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');
});

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

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};
}

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") + "
"); }); }