10.07.2017 Views

246996016-HTML5-Step-by-Step

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

JavaScript Events and jQuery 297<br />

You’ve now seen how to download jQuery, connect it to your page, and use it to select<br />

elements. And you just looked at a bonus example of a built-in function in jQuery called<br />

.fadeOut(). This leads to a more generalized discussion of functions in jQuery and Java<br />

Script. I promise that we’ll get to the cool stuff soon.<br />

Calling Functions with JavaScript<br />

Functions are groupings of code that perform a task. Here’s a function:<br />

function doSomething() {<br />

alert("Hello World");<br />

}<br />

That’s it, that’s all there is to functions. Well, almost. But there’s no reason to clutter the<br />

discussion of functions when a simple example will suffice. The .fadeOut() example gave<br />

you a glimpse at another important part of a function: a function argument. A function<br />

argument is a value that is passed to the function that determines how or what the function<br />

should do as it carries out its designed task. The .fadeOut() function uses the duration<br />

argument (passed as 5000 in the example at the end of the preceding section) to set<br />

the length of time that the function waits before it fades the element out.<br />

For example, here’s a showAlert() function that accepts a single argument called alertText,<br />

and then shows it in an alert dialog box:<br />

function showAlert(alertText) {<br />

alert(alertText);<br />

}<br />

Calling or invoking the function looks like this:<br />

showAlert("Showing an alert is fun and easy.");<br />

One other important aspect of functions is that they can return a value. Typically, the<br />

return value would be the result of whatever the function accomplishes, although<br />

the return value can be whatever you’d like it to be. For now, you’ll work on a typical<br />

example, where the return value is the logical result of the function. In this next example,<br />

the function adds two numbers and returns the result.<br />

function addTwo(num1, num2) {<br />

var result = num1 + num2;<br />

return result;<br />

}

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

Saved successfully!

Ooh no, something went wrong!