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.

Although no longer widely in use today, Dynamic HTML is a term that describes the technique of utilizing the web browser’s built-in Javascript API, as a means of dynamically modifying a web page. If a web developer wants to modify the page’s content, it can be done without having to request a separate web document from the web server. These techniques make possible greatly enhanced experiences for the visitors of web sites, however in its earliest days it was not always easy to use DHTML. The different web browser vendors often had different implementations of the DOM and, therefore, differing browser APIs for modifying a web page. It was an accepted reality by web developers then that multiple implementations of a dynamic web document were necessary to support all of the popular web browsers of the time.

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

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.

jQuery is a lightweight Javascript library, so using it does not incur a heavy cost in terms of the amount of code added, or the speed of the program execution, compared to what one would otherwise implement to dynamically modify a web page.

Getting jQuery

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.

jQuery.com

Figure 1 – Downloading from jQuery.com

Bower

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).

CDN

Figure 3 – Linking jQuery from a CDN

Linking local copy

Figure 4 – Linking in a local copy of jQuery

jQuery Selectors

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:

It probably seems like an odd-looking function, however $ is a perfectly valid Javascript identifier. $ is the global jQuery function. To access any jQuery function, you always begin with $. In this example, the selector is returning the element identified by #someIDattribute. If you are familiar with the DOM Javascript API, this is the same as what getElementByID does. jQuery does the same thing with its $() selector function, only with jQuery we use # to indicate that the identifier in the parameter is the value of an element’s 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?

tic-tac-toe

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.

HMTL Table tic-tac-toe

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:

or even

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.

jQuery Script tag

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.

jQuery Events

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.

Click Handler

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.

Developer console

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,

Where jQuery is utilized

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.

Clicking on the grid

Figure 11 – Clicking on the grid temporarily highlights the background and places X or O

Winning

Figure 12 – Winning mouse click changes the background color to green

Draw

Figure 13 – Game ending in a draw gets a different background color

CSS classes for background color

Figure 14 – CSS classes for background color

CSS classes

Figure 15 – The space marked has “gridspace” and “playing” CSS classes

winning game CSS

Figure 16 – A winning game modifies the CSS class of the winning grid spaces.

winning game CSS

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
  • o jQuery.get
    o jQuery.JSON
    o jQuery.post
    o .load

  • 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.








Leave a Reply

Your email address will not be published. Required fields are marked *