JQUERY
What is jQuery?
jQuery is a library of javaScript functions that allow you to easily specify the behavior of HTML elements while taking into account of the idiosyncrasies of each browser (vendor and version).
Why a JavaScript library?
To quote the official jQuery slogan: "Write less, do more." The role of a web developer is to create code that determines what will result from a user’s interaction with a web page. Web developers should not have to spend hours debugging browser quirks. Instead, they should be free to deal solely with the actions and the results. This is where a JavaScript library comes into play.
Overcoming browser differences
Different browsers handle DOM manipulation, transparency effects, and animation in different ways, requiring, in some cases, reams of code just to create a simple effect. Using a JavaScript library allows you to completely bypass all of those challenges, giving you access to an API (Application Programming Interface) that deals directly with the tasks you actually want to accomplish. All the challenges and issues common to JavaScript are dealt with behind the scenes, allowing you to integrate functionality without wondering whether or not it will work in a particular browser.
Unobtrusive JavaScript
Another impelling reason to use a JavaScript library is that all libraries allow you to include JavaScript in your pages unobtrusively, thus keeping your behavior layer (the JavaScript) separate from the content and presentation layers (the XHTML and CSS).
Accomplishing complex tasks with ease
Finally, a very powerful feature of any JavaScript library is its ability to manipulate any element or set of elements on a web page with just one line of code. Take, for example, the following HTML:
<div class="container">
<ul class="list">
<li>Text Here</li>
<li>Text Here</li>
<li>Text Here</li>
<li>Text Here</li>
<li>Text Here</li>
</ul>
</div>
Let’s say you wanted to use JavaScript to change the background color of the first list item element (<li>) in the unordered list above. Using pure JavaScript, your code would look something like this:
var myListCollection = document.getElementsByTagName("ul");
for (var i = 0; i < myListCollection.length; i++) {
if (myListCollection[i].className === "list") {
myListCollection[i].childNodes[0].style.backgroundColor = "blue";
}
}
Using jQuery, you can accomplish the same thing with just one, easy-to-maintain line of code:
$("ul.list li:first-child").css("background-color", "blue");
Understand CSS concepts
To be effective at writing jQuery code, you need to have a strong knowledge of CSS. This is because jQuery often utilizes CSS-based syntax to manipulate DOM elements. Here is a list of CSS selectors:
Most of the above CSS concepts should already be very familiar to any modern-day front-end developer, since any CSS layout would utilize these. jQuery not only incorporates the basic selectors (HTML tag, class, and ID), but it also uses descendant and child selectors, which aren’t supported by all currently-used browsers. But with jQuery, due to its built-in browser normalization, all selectors are supported equally.
Understand JavaScript concepts
In order to make full use of jQuery, it is a good idea to learn certain JavaScript concepts. Sure, you can do a ton of stuff in jQuery without knowing much about some of the concepts listed below, but you’ll have a bigger advantage in your jQuery development if you take the time to understand a few fundamentals, including:
- Object creation
- Properties of objects
- Adding functions (as methods) to objects
- Anonymous functions -
- Closures -
Again, it is not necessary to fully understand any of the above concepts in order to start working with jQuery, but your abilities with jQuery’s API will increase greatly if you understand one or more of the above concepts.
Referencing jQuery
You could look at the actual jQuery source code. It would be very large, nicely commented and using white space for readability, and having self documenting (long) variable names. That is nice if you are curious about what’s in jQuery, but for production usage, everyone uses the “minified” version of jQuery. This is a version where all white space and comments are removed, and all variable names have been converted to really short variable names (like a, b, c, …).
You could download either the source version or the minified version and include that in your website, but it is better if you use a CDN (content delivery network) and just link to jQuery. Since most websites use jQuery, if you reference a common CDN, most of your users will already have a cached copy of jQuery.
This is a (minified) version of jQuery that is hosted by Google:
<script src="
Or you could reference jQuery’s own CDN:
scriptsrc="//code.jquery.com/jquery-1.12.0.min.js"</script
The above line of HTML should appear before any actual jQuery code, otherwise you’ll get errors.
jQuery Syntax
The jQuery syntax is tailor made forselectingHTML elements and performing someactionon the element(s). The basic syntax is:$(selector).action()
- A $ sign to define/access jQuery
- A (selector) to "query (or find)" HTML elements
- A jQueryaction() to be performed on the element(s)
Examples:
- $(this).hide() - hides the current element.
- $("p").hide() - hides all <p> elements.
- $(".test").hide() - hides all elements with class="test".
- $("#test").hide() - hides the element with id="test".
But you can also specify when you want the behavior to happen by using jQuery events. For example, the following code means hide any paragraph whenever a user double clicks on that paragraph.
$("p").dblclick(function(){
$(this).hide();
});
You can also mix javaScript with your jQuery, as was done in the following example. This example means that the whenever the user’s mouse enters the HTML element with id="p1", and alert will pop up.
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
For a list of jQuery selectors, effects, and events, see these pages:
- jQuery Selectors (which HTML elements are effected):
- jQuery Effects (the effect or action to be applied):
- jQuery Events (when the effect kicks in):
Chaining commands
jQuery also allows developers to chain commands, stringing one after another. So, we could combine the previous two examples, as follows:
$("li a").fadeOut().fadeIn();
The above code will fade out all anchor tags nested within list items, then immediately fade them back in. The number of chained items is infinite (or within reasonably set limits), allowing for numerous commands to work on the same group of elements, each happening in succession.
Running code when the DOM is ready
The code examples we’ve discussed would run fine as long as they were included at the bottom of an HTML page. If, on the other hand, they were included in the head of the document, they would fail to work because, at that point, the document tree has not yet rendered.
jQuery allows us to run our code only when the DOM is ready. This is done by means of the $(document).ready handler. The beauty of this handler is that it doesn’t make the code wait until the entire page finishes loading, as would be the case with a typical window.onload event. With the (document).ready handler, your code will run as soon as the DOM tree is finished rendering, before all images and other media have finished loading, thus minimizing load time. Here is an example of deferring the jQuery code to wait until the DOM is ready:
$(document).ready(function(){
$("li a").fadeOut().fadeIn(); // all links inside of list items fadeout then fade in on page load
$("#p1").mouseenter(function() { // when a user mouses into the element with id=’p1’, alert
alert("You entered p1!");
});
});
The first and last line in the above code tells jQuery to run an anonymous function when the document tree is done rendering. Inside the document-ready function, there are two pieces of jQuery code. The first piece (code we saw previously), fades out links in list items then fades them right back in again. The next piece of jQuery says “what to do” (alert a message) if the user mouses into the element with id=’p1’. This entire code could be included in the <head> of the document or near the bottom of the page, and it would run exactly the same way.
These notes taken from a post byLouis Lazaris is a freelance web developer based in Toronto, Canada. He is a co-author of HTML5 and CSS3 for the Real World, published by SitePoint.
1