02.06.2013 Views

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

72<br />

CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS<br />

>>> $("", { "src":"not/an/image.png", ...ot be loaded!"); }) .appendTo("body");<br />

[ img image.png ]<br />

The image cannot be loaded!<br />

.scroll()<br />

If the document is scrolled, the scroll event is fired. To bind a h<strong>and</strong>ler to this event, use the .scroll()<br />

method:<br />

$(window)<br />

.scroll(function(){<br />

console.log("The window was scrolled!");<br />

});<br />

After executing this code, scrolling the browser window will cause a message to be logged in the<br />

console.<br />

Additionally, calling the .scroll() method without any parameters will trigger the scroll event to<br />

fire. After binding the preceding h<strong>and</strong>ler to the window, trigger the event <strong>by</strong> running the following:<br />

$(window).scroll();<br />

Executing this code will log the scroll event h<strong>and</strong>ler’s message in the console.<br />

H<strong>and</strong>ling Document Loading Events<br />

Often, JavaScript needs to wait until the document is ready before executing any scripts. Also, when<br />

users exit a page, sometimes it’s desirable to fire a function to ensure they meant to navigate away from<br />

it.<br />

.ready()<br />

The .ready() method is used in nearly every <strong>jQuery</strong> script as a safeguard against the script executing too<br />

early <strong>and</strong>, therefore, not performing properly. This method waits for the DOM to be ready for<br />

manipulation before firing its h<strong>and</strong>ler.<br />

Common practice is to make the entire script a callback function to be fired <strong>by</strong> the .ready()<br />

h<strong>and</strong>ler:<br />

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

// All <strong>jQuery</strong> functionality here<br />

});<br />

Additionally, the .ready() method accepts a parameter to use as an alias for the <strong>jQuery</strong> function.<br />

This allows you to write failsafe <strong>jQuery</strong> scripts that will work as expected even if the $ alias is given back

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

Saved successfully!

Ooh no, something went wrong!