10 Useful jQuery Techniques to Improve Your Code

May 14, 2013 · 35 comments

by Lars

usefuljquery

jQuery is known for making JavaScript things that used to be hard or almost impossible for most people simple and elegant. While the jQuery community is growing so is the number of plugins available for anyone to address nearly any client side need.

“Problem” is that using jQuery this way is so simple that getting to know the framework well is not really needed. Most people simply download a plugin and set it up according to the documentation. A good example of this is the many website using jQuery sliders today. The sliders are simply all over the place and there are plenty of cool plugins to choose from. Still I believe jQuery is worth investigating further and web every front-end developer and designer would benefit from knowing a bit more of what is going on under the shiny surface. This post will show you jQuery techniques and give you some insight and inspiration that you may use going forward.

If you find this post useful I will recommend that you take a look at these previous posts:


ElegantThemes
ThemeForest

Advertisement

#1 – Load the jQuery framework from Google or jquery.com

This is a tip you see in most jQuery pospts but it can’t hurt to repeat it. Google have been hosting several JavaScript libraries for a while now on Google Code and you may want to load it from them instead of from your server to take advantage of their great bandwith.

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

You can actually also load the latest jQuery version from jquery.com using this code:

<script src="http://code.jquery.com/jquery-latest.js"></script>

#2 How to make sure an image has loaded properly

You can do this by using the .load() method on an “img” element and put a callback function in it. In the example below the “src” attribute of an image tag is changed to load a new image and attaches a simple load function. This technique can fx. be useful when building a captcha form validator.

$('#myImage').attr('src', 'image.jpg').load(function() {
 alert('Image Loaded');
 //perform action that is dependant of image being fully loaded
});

#3 Easy Vertical Align

If you need to center an element to the documents height this jQuery snippet will be very useful. Using it is very simple as all you need to do is to add the class verticalcenter to the object that you want to center to your document. In the example below “TESTER” will be moved when “Do it” is clicked.

<div onclick="var doc_height = $(document).height();
  var el_height = $('.verticalcenter').height();
  $('.verticalcenter').css({'position' : 'relative' , 'top' :
  doc_height/2 - el_height/2});">Do it</div>
<div id="test2" class="verticalcenter">TESTER</div>;

#4 Replace a <div> with jQuery

A simple and possibly the most simple way is to use the replaceWith method.

$('#targetdiv').replaceWith('<div>going to be inserted!</div>');

#5 manipulate text with Regular Expressions and jQuery

You can perform quite power full actions with text by using regular expressions Regex. jQuery support Regex in a simple way and if you know Regex you will pick this up fast. Here is an example where the word “test” is removed from text in an element on the page. If you need to read up on Regex you may want to read this post.

<div onclick="var element = $('#test2'); element.html(element.html().replace(/\s+test/gi, ''));">Do it</div>
<div id="test2">Remove it: test</div>

#6 Opening links in new a window based on class or attribute

This jQuery technique is a simple and quick way to make all your external links open in new browser window. In order to make the code below work you need to add the attribute rel=”external” to your external links.

Another advantage of this trick is that target=”blank” attribute is not valid XHTML 1.0 Strict. If you are using the following code, you can achieve the same functionality without having validation problems.

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

Another way to control this and taking it a bit further by setting window size is shown below. Use the code by setting a class “popupwindow” on a link.

$('a.popupwindow').live('click', function(){
 newwindow=window.open($(this).attr('href'),'','height=220,width=170');
 if (window.focus) {newwindow.focus()}
 return false;
});

To open a link only as a tab you can use this code (requires a browser that support tabs). Use the code by setting a class “newtab” on a link.

jQuery('a.newTab').live('click', function(){
newwindow=window.open($(this).href);
jQuery(this).target = "_blank";
return false;
});

#7 Verify if an Element is empty

This is a simple way to test in jQuery if an element is empty. The code will print “Yes (?)” in an alert box because div #test is as empty as it can be.

<div onclick="alert($('#test').html() ? 'Certainly not' : 'Yes (?)');">Test it: Is target element empty?</div>
<div id="test"/>

#8 Simple but useful way to get the number of elements returned by a selector

This will return the number of matched elements. It’s simple and clean and typical for jQuery:

$('targetelement').size();

#9 Disable right-click contextual menu

There are a lot of examples and scripts in javascript covering this topic, but also this time jQuery makes you life much easier!:

$(document).ready(function(){
  $(document).bind("contextmenu",function(e){
    return false;
  });
});

#10 Parsing XML with jQuery (will be useful for AJAX operations)

XML is an important part of AJAX and AJAX is an important part of front end development. With jQuery, when you receive XML from a callback, you’re not actually getting raw text, you’re actually getting a DOM (document object model) that jQuery can traverse very quickly and efficiently to give you the data you need.

Lets take a look at some jQuery that will request a XML document on the server.

$(document).ready(function()
{
  $.ajax({
    type: "GET",
    url: "test_jquery_xml.xml",
    dataType: "xml",
    success: parseXml
  });
 });

Assuming you have the file “test_jquery_xml.xml” on the server you are ready to start parsing the XML. Lets assume the xml retrived looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<note type="public">
    <to>someone</to>
    <from>person</from>
    <heading>Reminder</heading>
    <body>Just a simple note!</body>
</note>
<note type="private">
<to>someone else</to>
    <from>another one</from>
    <heading>Reminder</heading>
    <body>Just another simple note!</body>
</note>

Accessing the xml data is simple and elegantly achieved in jQuery as show below.

function parseXml(xml) {
 //find every note and print the type
 $(xml).find("note").each(function()
 {
   $("#output").append($(this).attr("type") + "<br />");
 });
}

Output will be:
public
private

Previous post:

Next post:


Web Analytics