jQuery Basics
Get ready to add jQuery to your site by reading over these jQuery basics. Topics include how to load the jQuery document and some basic syntax
Before you add code to your HTML document, be sure to read our Getting Your HTML Ready for jQuery article. Once you have set up your HTML document for jQuery, you are ready to begin adding jQuery code to it. Here are some jQuery basics.
Loading the Document
Before you add your jQuery statements to your HTML document, there are a few things you need to do first.
To prevent your jQuery from executing before the document has finished loading, you need this jQuery event. Simply add:
$(document).ready(function(){ //Add your jQuery here }
And add your jQuery statements in place of the //Add your jQuery here comment.
Basic jQuery Syntax
Each jQuery line must begin with a ‘$’ sign. Follow this with a pair of parentheses enclosing the element you want to affect.
$(element)
Add a period and the name of the jQuery action you would like to apply to the element. Follow this with a pair of parentheses.
$(element).action()
A simple example of jQuery would be:
$(“.button”).hide()
This would hide all elements with the class=”button”. However, it is rare that we want to use jQuery just to hide or show something. The true power is when you tie these simple actions to events.
jQuery Events
Events can be used to trigger actions. Events can be things like clicking, hovering, or even when the page has finished loading. Tying actions to events is jQuery’s strength.
To create an action based on an event, you would do something like the following:
$(element1).event(function(){ $(element2).action(); });
For example, if you want to create a jQuery statement that will show paragraphs when a button is clicked, you would do something like this:
$(“#button”).click (function(){ $(“p”).show(); });
In this example, when the element with id=”button” is clicked, all <p> elements will be shown.
You can, of course, have more than one action tied to an event. For example, you could add $(“.navBar”).fadeOut(“slow”); causing the code to look like this:
$(“#button”).click (function(){ $(“p”).show(); $(“.navBar”).fadeOut(“slow”); });
The code would then show all <p> elements and slowly fade out all elements with the class=”navbar”.






