Introduction to jQuery
Once you get familiar with JavaScript you might be asking yourself if there perhaps a better way to do some things.
For example, document.getElementById(""); seems to be a little verbose when trying to
access elements within an HTML page.
jQuery is a library of JavaScript that offers a syntax
that is less verbose and very extensible. Javascript is not jQuery. jQuery
is JavaScript. jQuery extends JavaScript in a way that helps developers solve problem easier. In fact,
many libraries for JavaScript exist. In some ways libraries may seem like their own language/syntax rules entirely and sometimes
focus on solving very specific problems.
jQuery is a good language to start with when learning libraries in JavaScript. It
intermixes pure JS into
its syntax and can reduce the amount of typing required to implement functionality. Like
jQuery is a library of JavaScript, there is also a diverse ecosystem of libraries for jQuery
itself.
A Hello World Example
1. Include a <script>
tag into HTML page before including your own jQuery
- Content Delivery Network (CDN) - Include a
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
into
the <head>
OR just before the </body>
at the bottom
of your page. Remember, this script tag must be above any of your own jQuery.
- Alternatively, Download the JavaScript and
include it in your solution. You'll still need a
<script src="folder/path/jquery.min.js"></script>
in your HTML page.
2. Replacing window.onload = init;
In previous chapters we've used the window.onload = init; in combination
with a function init() {} to begin the handling JS in our page.
function init() {
alert("hello world");
}
window.onload = init;
Listing 12-2. Unobstruive plain JavaScript loading.
This script loads up the JavaScript after the window has loaded. jQuery has a similar
syntax for this below.
$(document).ready(function() {
alert("hello world");
});
Listing 12-3. jQuery loading when document is ready.
jQuery's version is waiting until the document is ready before executing. $(document).ready();
is similar to window.onload. The function() {}
within the ready() statement is a
function with no name; otherwise known as an anonymous function. It is similar to
function init() {} but doesn't have to be strictly defined. To some this may still be verbose; below
is another version of loading jQuery.
$(function() {
alert("hello world");
});
Listing 12-4. A shorter jQuery document.ready(); function.
You can still define a separate named function to hold code and pass it to the ready event.
function init() {
alert("Hello World");
}
$(init);
Listing 12-5. Using a named function.