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.

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

to another library using <strong>jQuery</strong>.noConflict() (which allows for multiple JavaScript libraries that use the<br />

$ alias to be used on the same project without issue).<br />

You can guarantee the $ alias will work using the following:<br />

<strong>jQuery</strong>.ready(function($){<br />

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

$("p").fadeOut();<br />

});<br />

Technically, any alias can be passed here:<br />

<strong>jQuery</strong>(document).ready(function(xTest){<br />

xTest("#bar").click(function(){console.log("Clicked!");});<br />

});<br />

This performs as expected, with no errors. There aren’t many cases in which this check would be<br />

necessary, but it illustrates how the alias works with the .ready() method.<br />

Finally, the <strong>jQuery</strong> function itself can be used as an alias for .ready():<br />

<strong>jQuery</strong>(function($){<br />

// actions to perform after the DOM is ready<br />

});<br />

.unload()<br />

The unload event is triggered whenever a user exits a page <strong>by</strong> clicking a link, reloading the page, using<br />

the forward or back buttons, or closing the window entirely. However, the h<strong>and</strong>ling of unload is not<br />

consistent across all browsers. And therefore should be tested in multiple browsers before being used in<br />

production scripts.To create a link to Google <strong>and</strong> attach an alert to the unload event, use the following<br />

code:<br />

$("", {<br />

"href":"http://google.com",<br />

"text":"Go to Google!"<br />

})<br />

.appendTo("#bar");<br />

$(window).unload(function(){<br />

alert("Bye! Google something neat!");<br />

});<br />

Execute this code, <strong>and</strong> click the new link. The alert fires, <strong>and</strong> you’re redirected to the Google home<br />

page.<br />

H<strong>and</strong>ling Event Attachment<br />

There are a whole slew of browser events triggered <strong>by</strong> the user, <strong>and</strong> <strong>jQuery</strong> provides several methods to<br />

h<strong>and</strong>le them easily.<br />

73

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

Saved successfully!

Ooh no, something went wrong!