10.07.2017 Views

246996016-HTML5-Step-by-Step

Create successful ePaper yourself

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

298 Chapter 16<br />

You call the function the same way as in the previous example, but this time, the function<br />

returns a value that you want to capture so that you can use it later, as shown here:<br />

var getSum = addTwo(2,5);<br />

With this code, the sum of the two numbers, 2 and 5, would be placed into the variable<br />

getSum, which you could then use later in the program.<br />

You’ll frequently use functions and pass arguments into functions, especially when<br />

working with event handling in JavaScript and jQuery. A JavaScript program of minimal<br />

complexity and size will typically use functions, as well.<br />

With all this background knowledge now complete, it’s time to look at working with<br />

events in JavaScript and jQuery. Events are actions like mouse clicks, keystrokes, and<br />

entering text into a form.<br />

Responding to Events with jQuery and JavaScript<br />

Responding to events with JavaScript is a complex process that involves working with<br />

multiple event models exposed <strong>by</strong> different Web browsers and multiple versions of the<br />

Document Object Model (DOM) to try to get the correct code to execute at the correct<br />

time. Therefore, rather than spend the next 30 pages on an in-depth discussion of event<br />

handling, I’ll shortcut the learning curve to show you how to handle events with jQuery.<br />

jQuery includes several event-related functions such as .click() for responding to mouse<br />

clicks, .submit() for responding to a form submission, .hover() to respond when a mouse<br />

cursor hovers over an element, and several others. In fact, the .ready() function that you<br />

saw earlier is an event handler. See http://api.jquery.com/category/events for more information<br />

on event handlers, including a list of the available jQuery handler functions.<br />

Earlier in the chapter, you saw the .fadeOut() function in use. That function ran when<br />

the page loaded (or more accurately, when the browser encountered the JavaScript).<br />

To make the element fade out when a user clicks it with the mouse, you need to<br />

attach a click event handler to that element. In jQuery, you do this with the help of<br />

the .click() function, which looks like the following example (I’ve highlighted the relevant<br />

code in bold):<br />

<br />

<br />

<br />

<br />

jQuery 101<br />

<br />

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

Saved successfully!

Ooh no, something went wrong!