There are three pieces to most examples of jQuery usage: the HTML document, CSS files to style it, and JavaScript files to act on it. For our first example, we'll use a page with a book excerpt that has a number of classes applied to portions of it. This page includes a reference to the latest version of the jQuery library, which we have downloaded, renamed jquery.js, and placed in our local project directory:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Through the Looking-Glass</title>
<link rel="stylesheet" href="01.css">
<script src="jquery.js"></script>
<script src="01.js"></script>
</head>
<body>
<h1>Through the Looking-Glass</h1>
<div class="author">by Lewis Carroll</div>
<div class="chapter" id="chapter-1">
<h2 class="chapter-title">1. Looking-Glass House</h2>
<p>There was a book lying near Alice on the table,
and while she sat watching the White King (for she
was still a little anxious about him, and had the
ink all ready to throw over him, in case he fainted
again), she turned over the leaves, to find some
part that she could read, <span class="spoken">
"—for it's all in some language I don't know,"
</span> she said to herself.</p>
<p>It was like this.</p>
<div class="poem">
<h3 class="poem-title">YKCOWREBBAJ</h3>
<div class="poem-stanza">
<div>sevot yhtils eht dna ,gillirb sawT'</div>
<div>;ebaw eht ni elbmig dna eryg diD</div>
<div>,sevogorob eht erew ysmim llA</div>
<div>.ebargtuo shtar emom eht dnA</div>
</div>
</div>
<p>She puzzled over this for some time, but at last
a bright thought struck her. <span class="spoken">
"Why, it's a Looking-glass book, of course! And if
I hold it up to a glass, the words will all go the
right way again."</span></p>
<p>This was the poem that Alice read.</p>
<div class="poem">
<h3 class="poem-title">JABBERWOCKY</h3>
<div class="poem-stanza">
<div>'Twas brillig, and the slithy toves</div>
<div>Did gyre and gimble in the wabe;</div>
<div>All mimsy were the borogoves,</div>
<div>And the mome raths outgrabe.</div>
</div>
</div>
</div>
</body>
</html>
Immediately following the normal HTML preamble, the stylesheet is loaded. For this example, we'll use a simple one:
body {
background-color: #fff;
color: #000;
font-family: Helvetica, Arial, sans-serif;
}
h1, h2, h3 {
margin-bottom: .2em;
}
.poem {
margin: 0 2em;
}
.highlight {
background-color: #ccc;
border: 1px solid #888;
font-style: italic;
margin: 0.5em 0;
padding: 0.5em;
}
After the stylesheet is referenced, the JavaScript files are included. It is important that the script tag for the jQuery library be placed before the tag for our custom scripts; otherwise, the jQuery framework will not be available when our code attempts to reference it.
Now, we have a page that looks like this:
We will use jQuery to apply a new style to the poem text.
This example is to demonstrate a simple use of jQuery. In real-world situations, this type of styling could be performed purely with CSS.