Getting Started with jQuery
A Guide to Getting Started with jQuery Libraries
jQuery, simply put, makes it easy to dynamically modify a web page document. Before we dive into jQuery, it is worth spending some time discussing some of the industry events that brought about its arrival.
The Document Object Model
In the earliest days of the world wide web, web pages were static, meaning they never changed in appearance once sent to the web browser. A web author would markup HTML by hand, carefully crafting each web page to be presented to a web site visitor. The retrieval of different web documents required a separate request for each to the web server. Even small differences between otherwise identical web documents either required the authoring of separate web documents, or the real-time generation of markup with a computer program that ran on the web server. Either way, a new request to the web server was needed in order to present different information to the viewer.
Eventually, the technologies behind the world wide web became more sophisticated, and web developers learned how to create Dynamic HTML (or DHTML), a technology that made it possible for the web browser to modify a web page without sending a new request to the web server. The Document Object Model (or DOM) became a standard means of organizing a web document’s content into a tree-like hierarchy within the web browser’s memory. The DOM establishes a parent-child relationship between the various HTML elements of the document, making it possible to consistently and predictably parse the markup.
The World Wide Consortium sought to standardize these technologies and, as time would reveal, it would take many, many years for browser vendors to agree on a standard that would work for most use cases. Even today, the WWC’s work in standardization continues.
jQuery is one solution to sparing the web developer from the browser-specific quirks that can make it difficult to uniformly create a dynamic web page that works across browsers. You write a jQuery program once and it will work for all of the major web browsers.
Some of jQuery‘s additional conveniences include a means of easily locating HTML elements within the document. Inserting new content into a web page or modifying a page’s content requires precisely locating where to perform such modification. jQuery uses a CSS-style selector mechanism to specify what you are searching for within the web document. CSS, or Cascading Style Sheets, is another web standard for specifying how web documents appear. jQuery selectors emulate the syntax used by CSS to unambiguously specify which parts of the web document to modify.
There is only one file to install to use jQuery within your web application. You can obtain it directly from jQuery.com (Figure 1) or with Bower, a repository for reusable web component (Figure 2). The installed file is also available in in minified format.
Figure 1 – Downloading from jQuery.com
Figure 2 – Installing with Bower
If you prefer to use a Content Delivery Network (or CDN), you can link directly to it. Either way, a single <script> tag is all that is required to integrate jQuery into your HTML file (Figures 3 and 4).
Figure 3 – Linking jQuery from a CDN
Figure 4 – Linking in a local copy of jQuery
As mentioned earlier, jQuery uses CSS-style selectors to locate individual elements with the document. One of the easiest and most commonly-used jQuery selectors is a function for returning an element with a specified id attribute:
Many times, however, we are not fortunate enough to have a unique id attribute for the element we want to access. Or, sometimes we want to access multiple elements that share the same characteristics. We will have to identify this element or these elements by describing them in some other way.
Say we have 3X3 grid, as in the game of tic-tac-toe (Figure 5). How could we select every grid space on the game board?
Figure 5 – You know how to play tic-tac-toe, right?
If every grid space was assigned a CSS class of gridspace (Figure 6), specifying a selector of .gridspace would return all of the matching elements.
Figure 6 – an HTML table as a tic-tac-toe grid
Selecting all of the spaces in the tic-tac-toe grid with jQuery could look like:
if you wanted to specify only td elements bearing the CSS class of gridspace. A dot (.) preceding the identifier notifies jQuery that you are selecting an element with a CSS class.
jQuery provides a great deal of flexibility in selecting an HTML element or a group of HTML elements. We will explore more of these throughout this tutorial.
jQuery UI Widgets
The jQuery community has done a great deal to expand the capability of core jQuery, including the addition of hundreds of user interface plugins to assist in the programming of user interfaces, from the utilitarian to the purely aesthetic. You can browse the repository at jQuery-ui.com. There, you can download the latest stable version, or you can customize your download by selecting which widgets you want if you don’t want to download the entire library. Or, as before, you can opt to use bower to download them.
Figure 7 – Don’t forget to add a script tag for jQuery-ui
For example, say we wanted to insert a tic-tac-toe marker (X or O) onto one of the grid spaces. With the standard selector, we could do so with
If we want to go a bit further and liven up this game, there is a fun special effect that could briefly highlight the mark just placed.
And if we want to celebrate a victorious tic-tac-toe game, how about animating the winning spaces?
jQuery plugins such as these are tremendous time savers. There are UI widgets to handle menus, dialog boxes and many other common user interface features.
Tic-tac-toe isn’t much fun if there isn’t a way to interact with the web page. The natural thing to implement is to allow the player to mark an empty grid space by simply clicking on it. Fortunately, jQuery provides a means of handling mouse events such as these, click.
Figure 8 – Assigning a mouse click handler to every grid space
Because jQuery selectors are so flexible, you can assign an event handler to one element, or the same handler to a collection of elements that match the same criteria. Figure 8 illustrates that the first argument passed to click is the event itself. jQuery events are very similar to the standard DOM event objects, but are augmented with additional jQuery attributes that are useful for identifying which HTML element triggered the event. Figure 9 shows that one way to identify which element was clicked on is with Event.currentTarget.
Figure 9 – Developer console displaying mouse click event
Taking a closer look at clickHandler (Figure 10), as it pertains to our hypothetical tic-tac-toe game,
Figure 10 – clickHandler updates the grid’s appearance
it is a pretty busy routine. Figure 10 demonstrates several instances where jQuery is utilized.
Lines 44 – 45 are another instance of dynamically modifying display text. Here, in response to a mouse click, the player is marking (with an X or an O) a space on the play grid. The mark is temporarily highlighted, and then set to its permanent background color. See Figures 11 – 13 for a mouse click in action for various game states.
Lines 52 – 59 are about dynamically modifying the CSS class attribute to change the background color of a marked grid space. Depending on the game’s status (playing, draw or winner), a different CSS class value is returned and dynamically assigned to the HTML element of a grid space (Figure 14). Every time an X or O is placed on the grid, the entire play area is re-evaluated to determine the game’s status and each space is colored appropriately. A console log of element inspection is shown in Figures 15 – 17. As the game status changes, the CSS class attribute for each td element can change, thus affecting the background color displayed.
Lines 62 – 64 dynamically modify the game’s displayed status (“ready”, “playing”, “draw” or “winner”) and animate the text when the game ends in victory for one of the players. This is also depicted in Figures 15 – 17.
Figure 11 – Clicking on the grid temporarily highlights the background and places X or O
Figure 12 – Winning mouse click changes the background color to green
Figure 13 – Game ending in a draw gets a different background color
Figure 14 – CSS classes for background color
Figure 15 – The space marked has “gridspace” and “playing” CSS classes
Figure 16 – A winning game modifies the CSS class of the winning grid spaces.
Figure 17 – A game ending in draw changes the CSS class of all spaces to indicate a draw.
In each of these cases, a selector is first used to reference the desired element or elements, and then the returned result executes an additional method for affecting the desired modification to the web page.
A Few Important jQuery Methods
The jQuery API is large and, together with the ever-growing community repository of plugins, it continues to expand in its capability. Fortunately, it is also very easy to use because its programming model is centered around CSS-styles selectors to locate and modify HTML elements. This programming model is consistent throughout, and makes jQuery very easy to pick up, especially if you are already familiar with CSS.
Here are some additional, notable methods and properties that you are likely to run into.
- .ready – Specify and execute a handler when the DOM is fully loaded
- jQuery.ajax – Issuing an asynchronous HTTP request
- Shorthand methods that correspond to HTTP request types
- event.target – the HTML element that triggered the event
- .change – trigger or assign a handler to the change event for form elements
- .submit – trigger or assign a handler to the submit event
You can read about these, as well as the rest of the API, at the jQuery API Documentation.