Introduction to jQuery

JavaScript is a useful tool for creating dynamic content on web pages however a lot of code in JavaScript is the same old getting HTML elements and setting values, this becomes a laborious tasks which distracts the developer from their purpose. There is a solution to this problem jQuery. jQuery is a lightweight JavaScript library that eases JavaScript development. jQuery takes a lot of the common tasks that require the same lines of code and encapsulates them into some simple method calls. jQuery makes manipulating the document object model easy and facilitates simple animations without too much hassle.

As jQuery is an external library the web browser does not know about it. Like any other JavaScript file that you want to use the jQuery library must be included in the HTML document. The jQuery library comes in two version, the production version and the development version. They contain exactly the same features only that the production version is compiled into optimised code which is almost impossible to read whereas the development code is easy to read and works 'nicely' with the debugger. For this module it is recommended that you use the development version.

To include jQuery into a HTMl document the script HTML element is used. There are two possible locations for including jQuery into a webpage. Either jQuery can be hosted in the same directory as the HTML document or it is possible to use a content delivery network (CDN). A content delivery network is a set of servers whose responsibility it is to serve content reliably and quickly. The advantage of using CDN's is that if the user visits multiple web sites that all use the same set of libraries then the web browser will have cached the libraries locally which increases site performance by reducing page load time. To use Google's CDN the following code should be included in the header of the HTML document.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

jQuery Syntax

The jQuery syntax is designed to make selecting HTML element easy. The basic syntax for selecting an element is;

$(selector).action()

The selector can be any CSS selector. The action method performs the action on whatever HTML element has been selected. One obstacle with jQeury is that if it is placed in a script HTML element then it will run as the browser loads the page, however, some of the element may not have been encountered by the browser. To remedy this problem all jQuery code should only be executed once the document object model has been loaded. To implement this remedy any jQuery code should be placed inside the following piece of code.

$(document).ready(function(){

   // put jQuery code here

});

jQuery Selectors

jQuery uses CSS selectors to select which HTML element to modify. All selectors in jQuery used the $ symbol with parentheses. In fact this is just a special method implemented in the jQuery library. As CSS selectors have been covered in previous section we will only provide a recap in this section. To select all div HTML elements in jQuery the following code is used:

$("div")

The result is any action that is executed will be applied to all div elements. In the following example the div element is hidden when the button is pressed and is made visible when the other button is pressed. The above example uses an id CSS selector to get the two buttons.

To select a HTML element or a set of HTML elements based on the class attribute the following notation is used.

$(".test").hide();

More jQuery Selectors

Syntax Description Example
$("*") Selects all elements
$(this) Selects the current HTML element
$("p.example") Selects all p elements with class="example"
$("p:first") Selects the first p element
$("ul li:first") Selects the first li element of the first ul
$("ul li:first-child") Selects the first li element of every ul
$("[class]") Selects all elements with a class attribute
$("tr:even")/$("tr:odd") Selects all even/odd tr HTML elements

jQuery events

Event is jQuery are the same as in JavaScript only the notation is slightly different. An event allows the web page to respond to some user interaction with the web page. In previous examples we have seen how to use the click event, which is fired when the mouse is clicked on an HTML element. There are two ways to add an event listener in jQuery, either using anonymous functions or a named function. The syntax for both is shown below.

function exampleFunc(){
    // something snazzy here
}
// using a named function
$("p").click(exampleFunc);

// using an anonymous function
$("p").click(function(){
  // something snazzy here
});

Whether anonymous functions or named functions are used the result is the same. Sometimes it makes for more readable code to use anonymous functions. The jQuery event documentation specifies the possible events that are available. Some of the common events are listed below.

Method / Property Description Example
bind() Attaches event handlers to elements Try it on jsFiddle
blur() Handles the blur event. The blur event is triggered when an input element looses focus. Try it on jsFiddle
change() Handles the change event. The change event is triggered when the value of a HTML element changes. Try it on jsFiddle
click() Handles the click event. The click event is triggered when the user clicks on a HTML element. Try it on jsFiddle
dblclick() Handles the double click event. The dblclick event is triggered when the user double clicks on a HTML element. Try it on jsFiddle
focus() Handles the focus event Try it on jsFiddle
focusin() Attaches an event handler to the focusin event Try it on jsFiddle
focusout() Attaches an event handler to the focusout event Try it on jsFiddle
hover() Attaches two event handlers to the hover event Try it on jsFiddle
mousedown() Handles the mousedown event Try it on jsFiddle
mouseenter() Handles the mouseenter event Try it on jsFiddle
mouseleave() Handles the mouseleave event Try it on jsFiddle
mousemove() Handles the mousemove event Try it on jsFiddle
mouseout() Handles the mouseout event Try it on jsFiddle
mouseover() Handles the mouseover event Try it on jsFiddle
mouseup() Handles the mouseup event Try it on jsFiddle

jQuery Effects

jQuery makes using animation easy. It is possible to apply hide, show, slide, fade and other interesting animations effects to HTML elements. These effects have become apart of the Web experience for many Web users. Some of the previous example have used the show and hide effects. To apply the effects on an HTMl element, first select the HTML element they invoke the appropriate method. The example below shows how to apply the hide/show effect.

The above example uses two separate event handlers, jQuery has a single method that does the same but only uses one button. The toggle method will show a hidden item or hide a visible item depending on whether it is currently visible or not.

A summary of some of common effects are provided in the table below.


Method Description Example
delay() Sets a delay for all queued functions on the selected elements Try it on jsFiddle
fadeIn() Fades in the selected elements Try it on jsFiddle
fadeOut() Fades out the selected elements Try it on jsFiddle
fadeToggle() Toggles between the fadeIn() and fadeOut() methods Try it on jsFiddle
hide() Hides the selected elements Try it on jsFiddle
show() Shows the selected elements Try it on jsFiddle
slideDown() Slides down the selected elements Try it on jsFiddle
slideToggle() Toggles between the slideUp() and slideDown() methods Try it on jsFiddle
slideUp() Slides up the selected elements Try it on jsFiddle
toggle() Toggles between the hide() and show() methods Try it on jsFiddle

For a complete list of effect see the jQuery documentation.

jQuery DOM manipulation

JavaScript is mostly used to manipulate the DOM to provide the appearance of dynamic content on a web page without having to make a request to a web server. jQuery simplifies manipulating the DOM. There are three methods that access the content of an HTML element. The methods are:

  • text() : gets/sets the content of the selected element.
  • html() : gets/sets the content of the selected element including the HTML markup.
  • val() : gets/sets the value of a form field.

Modifying attributes

To get an attribute of an HTML element the attr() method is used. The method takes one argument which is the name of the attribute to get. The example below shows how to get the href attribute of an a HTML element.

To change the value of the text,html and val of an HTML element the text(),html() and val() are used respectively. Each of the methods take one argument which is the value to set the content to. In a similar manner the attr() method is used to set the value of an attribute on a HTML element. To use the attr() method to set the value of an attribute the method takes two arguments, the first argument is the name of the key to set and the second argument is the value to set the attribute to.

Modifying the structure

To be able to add and remove elements from a HTML document using jQuery the append() and remove() methods are used respectively. These methods will add and remove then HTML element and all of its nested HTML elements. To be able to add an element to a HTML document first you must get the element that is to be the parent of the element you are adding, this can be done using the selectors. A HTML element may contain a list of HTML elements, this list of elements is ordered. When the new element is added it is possible to specify where in this list the element will be added. The following methods are used to specify where the element is added:

  • append() - Inserts content at the end of the selected elements
  • prepend() - Inserts content at the beginning of the selected elements
  • after() - Inserts content after the selected elements
  • before() - Inserts content before the selected elements

To remove elements from a HTML document the remove() or empty() method can be used. The remove() method removes which ever element/elements match the selector. The empty() method removes all elements from the HTML element/elements that match the selector.

Modifying style

Using jQuery it is possible to modify the style of elements by either adding CSS classes to HTML elements or by adding style directly to a HTML element. The addClass() method adds a CSS class to whichever HTML element/elements match the selector. The removeClass() method removes a CSS class from whichever HTML element/elements match the selector.

To apply a CSS rule directly to a HTML element the css() method is used. The method takes two arguments, the first being the CSS attribute and the second being the value to set the specified attribute to. Any CSS attribute that was covered in previous sections can be added this way.

jQuery DOM navigation

Navigating the DOM using jQuery is must simpler than navigating the DOM in plain JavaScript. Sometimes the CSS style selectors are not sufficient to select a HTML element because you wish to select an element based on context, that is, you may want to select all div elements that contain at least two paragraphs. To be able to do this type of selection it is necessary to be able to navigate the DOM. As was mentioned in previous section the DOM is a tree like structure, each element has a parent (except the root) and some elements may have children. The jQuery documentation on traversing contains all the possible method available.

A common task in JavaScript is to apply some modification to the parent element of some element. In jQuery this is easy, the parent() method returns the HTML element.

Another common task is to apply some modification to all child elements of some element. In jQuery this is done using the children() method. The example below applies a modification to all paragraph elements that are a child of a div.

The find() method allows the retrieval of a specific type of element that is a child of another element.