Time for action – getting ready for jQuery
Perform the following steps to start with your first jQuery script:
- Set up your files and folders just like we did in the previous exercise. Inside the
<body>
tags of the HTML document, add a heading and a paragraph, as follows:<body> <div class="content"> <h1>My First jQuery</h1> <p>Thanks to jQuery doing fancy JavaScript stuff is easy.</p> </div> </body>
Feel free to add some CSS code to the
styles.css
file in thestyles
folder. Style this however you'd like. - Next, open up that empty
scripts.js
file we created earlier and add this bit of script to the file:$(document).ready();
What just happened?
Let's take this statement one thing at a time—first, the dollar sign. Really? What's this doing in JavaScript?
The $
here is just a variable—that's all. It's a container for the jQuery function. Remember how I said we might use a variable to save ourselves a few keystrokes? The clever writers of jQuery have provided the $
variable to save us from having to write out jQuery every time we want to use it. The following code does the same thing that the preceding script did:
jQuery(document).ready();
Except that it takes longer to type. jQuery uses the $
sign as its short name because it's unlikely that you'd call a variable $
on your own as it's an uncommon character. Using an uncommon character reduces the chance that there will be some sort of conflict between some other JavaScript being used on a page and the jQuery library.
So, in this case, we're passing document
to the jQuery
(or $
) function because we want to select our HTML document as the target of our code. When we call the jQuery
function, we get a jQuery
object. In JavaScript, we'd say that the jQuery
function returns a jQuery
object. The jQuery
object is what gives the jQuery
library its power. The entire jQuery
library exists to give the jQuery
object lots of properties and methods that make our lives easier. We don't have to deal with lots of different sorts of objects; we just have to deal with the jQuery
object.
The jQuery
object has a method called ready
. In this case, the ready
method will be called when the document is loaded into the browser and is ready for us to work with. We can pass a function to the ready
method to say what should happen. So $(document).ready()
just indicates when the document is ready.