In the last article, I showed how to use jQuery to select elements in the Document Object Model (DOM) of a web page. In this article, I will show things you can do with those selections.
Calling Methods on Selections
We can call methods on the list of objects returned by a selection simply by appending a dot, followed by the method call and any arguments to the selection syntax. For example, the following jQuery will hide all the anchor tags on a page:
$(“a”).hide();
Binding Functions to Selections
One of the powers of jQuery is the ease with which we can bind a function to the events of an object, so that this function executes whenever the event fires. To do so, simply append a selection with a dot followed by the name of the event; then, pass the function as an argument to the event, as shown below:
$(selection).eventname(function(){
…
}
For example, the click event fires when a user clicks on a page element. The following sample binds a function to the click event of an element with the ID “Div1”:
$(“#Div1”).click(function(){
…
}
The (document).ready event
The document variable is defined within the jQuery script. Selecting this variable with $(document) will return the document as a whole. The most common use for this selector is to bind a function to the document’s ready event. The syntax for this is
$(document).ready(function(){
…
});
I have omitted the body of the function in this case, but notice the anonymous function declaration. In JavaScript, we don’t need to assign a name to a function if we are binding it to an event – we only need to pass that function to the method name. This is common syntax in JavaScript.
In fact, binding a function to the document ready event is so common, that its syntax can be shortened to simply surrounding a function with parentheses preceded by “$”, as shown in the following snippet, which does the same thing as the previous snippet
$(function(){
…
});
Putting it All Together
We can nest functions in jQuery and we often do so by binding code to events when the document.ready event fires, as in the following example:<script type="text/javascript" src="jquery-1.10.2.min.js">script>