06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8<br />

You can't use jQuery before the page is completely loaded. As jQuery will need to<br />

know all the nodes of the DOM structure, the entire DOM has to be in-memory.<br />

To ensure that the page is completely loaded and in a state where it's ready to be<br />

manipulated, we can use the $(document).ready() function. Here, the IIFE is<br />

executed only after the entire documented is ready:<br />

$(document).ready(function() {<br />

$('#greeting').html('Hello World Martian');<br />

});<br />

This snippet shows you how we can associate a function to jQuery's .ready()<br />

function. This function will be executed once the document is ready. We are using<br />

$(document) to create a jQuery object from our page's document. We are calling the<br />

.ready() function on the jQuery object and passing it the function that we want to<br />

execute.<br />

This is a very common thing to do when using jQuery—so much so that it has its<br />

own shortcut. You can replace the entire ready() call with a short $() call:<br />

$(function() {<br />

$('#greeting').html('Hello World Martian');<br />

});<br />

The most important function in jQuery is $(). This function typically accepts a<br />

CSS selector as its sole parameter and returns a new jQuery object pointing to the<br />

corresponding elements on the page. The three primary selectors are the tag name,<br />

ID, and class. They can be used either on their own or in combination with others.<br />

The following simple examples illustrate how these three selectors appear in code:<br />

Selector CSS Selector jQuery Selector Output from the selector<br />

Tag p{} $('p') This selects all the p tags<br />

from the document.<br />

Id #div_1 $('#div_1') This selects single elements<br />

that have a div_1 ID. The<br />

symbol used to identify the<br />

ID is #.<br />

Class .bold_fonts $('.bold_fonts') This selects all the elements<br />

in the document that have<br />

the CSS class bold_fonts.<br />

The symbol used to identify<br />

the class match is ".".<br />

[ 187 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!