Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

Top 10 jQuery Tips for Novices

  • Print
  • + Share This
  • 💬 Discuss
Where should a novice jQuery developer start? Jay Blanchard, author of jQuery and jQuery UI: Visual QuickStart Guide, suggests that you start with his ten jQuery tips for novices.

For Web developers and designers who have worked mainly in HTML and CSS, learning jQuery might seem daunting. For many, it is their first foray into what is really a programming language.

So where should you, a novice jQuery developer, start? The answer can be the subject of holy wars on social media outlets, but almost everyone agrees that on one thing – jQuery is JavaScript. That leads to your first tip:

Tip 1: Learn JavaScript

You don’t have to become an expert yet, but the best thing that you can do as you start your journey to learning and using jQuery is to learn and use the language that the library is built on. One of the best places to learn is http://http://www.codecademy.com . It’s free and you can take courses for JavaScript and jQuery there.

If you want to dig into jQuery right away though, let’s look at some habits that can make your life much easier when it comes to developing websites and applications using this fantastic library.

Tip 2: Use a CDN

You should use a (Content Delivery Network) for serving the jQuery core files and back it up with a fallback in case the CDN is not available. This serves many purposes, not the least of which is faster loading of your websites for those visitors who may have already cached a version of jQuery from one of the CDNs.

For the fallback, you should download and store the same version of the jQuery core files on your web server. Then using code such as the following snippet in the head section of your HTML document you can test for the existence of the CDN loaded jQuery, and if that fails you will load the fallback version from your server.

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
    document.write(unescape("%3Cscript src='path/to/jquery-1.8.3.min.js'
 type='text/javascript'%3E%3C/script%3E"));
}
</script>

A word of caution though–many CDNs offer a jQuery file typically called jquery-latest.js or something similar. Don’t use this in your CDN request because automatic upgrades to the newest version of jQuery in the CDN may break code that you have put in place on your websites and web applications. Always specify which version of jQuery you are using and make sure that all of you code is tested and working properly with that version of the core files.

Tip 3: Learn the difference between ID attributes and class attributes in your HTML markup

Each element in a web page can have an ID, and each ID in a page must be unique. In other words no two elements in a page can have the same ID. Classes are different; they may be assigned to any element in a page and may be assigned to all elements.

When using jQuery to address a page element with an ID or class always use the CSS (Cascading Stylesheet) syntax, ‘#’ prefix for IDs and the ‘.’ for classes in your selector:

$(‘#elementID’)
$(‘.elementClass’)

Tip 4: Cache your selectors

If you’re finding yourself using a selector over and over again, it is better to cache those objects in a variable so that jQuery doesn’t have to perform the lookup each time that you call on those objects.

var cleverVariableName = $(‘selectedElements);

Sometimes you might have a several very clever variable names though, and some of them might not be jQuery objects, which leads to my next tip.

Tip 5: Prefix your cached jQuery objects

Prefix your cached jQuery objects with a character or two that makes those variables easily identified as jQuery objects. Because selectors are normally prefixed with the ‘$’ (the alias for jQuery in a normal installation) I like to prefix my variables holding those selectors with the ‘$’ too:

var $moreCleverlyNamedVariable = $(‘selectedElements’);

Now that the prefixes match, it is easier to remember when coding actions for those elements as the scope of the page grows.

Tip 6: Chain method calls where possible

As a simple example, imagine that you have a paragraph of text that is hidden to start with. Normally the text color would be black, but because you are going to fade this paragraph in you want it to be noticeable, so you decide to give it a reddish color before fading it in. I’ve described two methods–changing the color with CSS and fading the paragraph into view. By chaining you make your code easier to read and more efficient:

$(‘p’).css({‘color’: ‘#990000’}).fadeIn(‘slow’);

Furthermore you can break up lengthy chains by placing each method on its own line:

$(‘p’)
    .css({‘color’: ‘#990000’})
    .fadeIn(‘slow’);

By breaking it up, especially if you are chaining a large number of methods together, you can make the instructions easier for you to read and follow. It is especially helpful when traversing the elements to locate a particular element to act upon within a complex web layout.

Tip 7: Understand the difference between attributes and properties

HTML attributes and properties are two different things, so make sure you use the right jQuery method--either attr() or prop()--to handle them, especially if you’re using the newest versions of jQuery.

An attribute’s value may only be a string where a property can be of any type, including objects. For example, the checked property is a Boolean object while the style property is an object with individual properties for each style. Some properties have numerical values. On the other hand id, name, and class only accept strings, so that would make them attributes modifiable by the attr() method.

Tip 8: Learn how to delegate events

As a newcomer to jQuery you’re going to eventually want to include content from another source in your web pages via Ajax. Once you do that you’ll also wonder why your beautifully crafted jQuery code seems to have no affect on those elements. The answer is quite simple:

The jQuery code is not aware of the new content because that content did not exist when the jQuery code was executed during the original page load.

The solution is really very simple. jQuery provides a method called on() that can be used to direct event capturing as an event bubbles up the DOM tree. As an example let’s say that you have a link that is in a paragraph that resides in a div within a div, like this:

<div id=”outside”>
    <div class=”inside”>
        <p class=”added_by_ajax”>
            <a class=”link_added_by_ajax” href=”myLink.html”>click</a>
        </p>
    </div>
</div>

The uppermost div with a class of “outside” existed in the page at the time the page was originally loaded, and all events in the children elements will work their way up (the proper term is event bubbling) the tree until they reach this div. (They continue bubbling up the tree until they reach the root of the document, but for this example and the sake of brevity let’s not go into that.) In this example the content being loaded by Ajax is the paragraph, so how do you get the jQuery code to react to this properly? You delegate the event to the “outside” div using on():

$(‘.outside’).on(‘click’, ‘link_added_by_ajax’, function() {
    // do something with the event
});

By doing this you attach the event handling to an element that existed at the time the page originally loaded, and any event delegated to that event will be handled by your existing jQuery code.

Tip 9: Become a plugin afficianado!

There are jQuery widgets, called plugins, that have been designed to solve any number of issues you may encounter when adding jQuery to your websites. First and foremost is the jQuery UI library, which features items like tabs, date pickers, accordions and many other nifty little plugins that the jQuery team has hand picked and maintained to work hand in hand with the jQuery core library.

The next best place to look for plugins is the jQuery Plugin Registry. Plugins by third parties (maybe you’ll have yours added here some day!) are categorized and searchable to make it easier for you to locate, download and use the best plugins available to help you create highly interactive and versatile websites and applications.

Tip 10: Know where and how to ask for help

The jQuery team hosts a forum where you can post questions and code to get help solving problems and have discussions on every aspect of the jQuery universe. The atmosphere is very loose and conversational and can be a friendly environment for jQuery beginners to participate in.

If you want something a little more focused, the fine folks at StackOverflow have created a forum that is designed to provide specific answers to well asked questions. If you decide to seek answers here make sure to include the problem code and markup in your question or you’ll find yourself quickly under the gun for clarification. If there is any doubt about asking a question on Stack Overflow read the excellent blog post, http://http://www.whathaveyoutried.com, by Matt Gemmel.

Now that you’re armed with some really helpful tips on jQuery you’re ready to get on that carnival ride. Grab your tickets and let’s go!

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus

Related Resources

There are currently no related titles. Please check back later.