Lesson 8: Introduction to JavaScript and jQuery

web10.psd

In this lesson, you’ll learn the fundamentals of adding interactivity to your pages with JavaScript and the jQuery JavaScript library.

What you’ll learn in this lesson:

  • An overview of how to use JavaScript
  • How to use the jQuery JavaScript library

Starting up

You will work with several files from the HTML5_08lessons folder in this lesson. Make sure you have loaded the HTML5lessons folder onto your hard drive from www.digitalclassroombooks.com/HTML5. See “Loading lesson files” in the Starting Up section of this book.

3054.jpg This lesson uses the TextWrangler text editor to create the markup, but you can use any text editor and achieve the same results.

Interactivity on the Web

The Web is an interactive medium by nature, and hyperlinks are good examples of this. Even the most basic website requires user interaction, and the decisions made by the designer can affect the user’s perception of the site as well as their experience. HTML offers very few possibilities for interaction, but by adding CSS, you have options such as CSS rollovers and the ability to style hyperlinks. CSS does have certain limitations, which you can overcome by using the JavaScript scripting language and interactive media such as Flash.

1562.jpg

A form button with no JavaScript attached will do nothing when the user clicks on it.

Adobe Flash

Flash was designed in the early days of the Web to perform interactive tasks. It began as a way to create and share animations on the Web, and quickly grew to include sophisticated interactivity and the ability to display and control video. In recent years, alternative technologies, such as Microsoft Silverlight and the HTML5 family, have emerged as an alternative to Flash and share many of its benefits and disadvantages. The functionality and role of Flash and Silverlight often overlap with HTML, CSS, and JavaScript and sometimes even replace them.

JavaScript

JavaScript lets you extend the functionality and appearance of a website through a range of interactive tasks that vary from the simple, such as validating a form, to the complex, such as animated slide shows. JavaScript is a scripting language that is more complicated to learn and use than HTML and CSS. The availability of JavaScript libraries has made it easier to add interactive elements, which has resulted in an increase in the number of developers using JavaScript. JavaScript libraries provide interactive functions, largely hidden from view from the designer, that can be added to a page with little effort. Later in this lesson, you will learn about jQuery, one of the JavaScript libraries.

The next part of this lesson provides an overview of working with JavaScript technology, and you will create an interactive photo gallery.

JavaScript basics

JavaScript is a scripting language that has its own syntax and structure. A full description of JavaScript and how to use it is beyond the scope of this book. This lesson provides a brief introduction, but there are several books and training courses where you can learn about JavaScript. Some references are listed below.

In this lesson, you will gain a basic understanding of how JavaScript interacts with HTML, which will serve as a foundation you can apply to more advanced scripting languages, such as PHP. In the following steps, you will work with a simple form to understand some of the basic concepts of JavaScript.

1 In your text editor, choose File > Open and navigate to your HTML5_08lessons folder. Choose the 08_subscribe.html file, and then click Open. To ensure you have a backup copy of this file, you’ll save the document with a new name.

2 Choose File > Save As and name this file 08_subscribe_work.html. Be sure to save this file in the HTML5_08lessons folder.

Take a moment to examine the HTML code; note that it is completely created with HTML and as such, lacks functional interactivity.

3 Preview the page, and then click the Submit button. Nothing happens, except for the default behavior of the button, which is a non-functional element on your web page.

1587.jpg

HTML cannot validate whether a form field was filled out; you need JavaScript for this functionality.

You need JavaScript to make this button interactive. HTML lets you perform activities, such as control the text that appears on the button, but offers no interactivity control. You will add JavaScript code to trigger a window to appear in your browser and prompt you to type your name. When you type your name and click OK, your JavaScript code will write your name on the page.

4 Close your browser and in your text editor below the <title> tag in your page, type the following code:

<script type="text/javascript">

</script>

You need to indicate in your HTML that you want to use JavaScript, just as you do with CSS. You can place these instructions anywhere in the HTML code, but best practice is to add them to the <head> section of your page.

5 Add the following code:

<script type="text/javascript">

function show_prompt()

</script>

A function in JavaScript is code that will be executed by an event on the page. In this case, the code is called show_prompt(), and it is unique code that tells your web browser to open a small pop-up window. The event that triggers this function is the user clicking the Submit button.

The show_prompt() function needs more information to work.

6 Add the following code below the function:

<script type="text/javascript">

function show_prompt()

{

var name=prompt();

}

</script>

In this line of code, you have declared a variable and its value. This variable, called name, obtains its value from the prompt function. One line of code is the minimum amount of information you need to make something happen in your JavaScript.

To trigger the JavaScript code, you need to add an instruction to your HTML button that describes how to trigger the code and what function to use.

7 Add this code to the HTML for your button:

<input type="button" onclick="show_prompt()" value="Submit" />

The onclick code is known as a JavaScript event and the value "show_prompt()" is the JavaScript function that you declared in step 5 in your <script> tag. Now, you have completed a logical chain that essentially says: “When a user clicks on this Submit button, call the show_prompt function. When the show_prompt function runs, it will call another function named prompt.”

8 Save your file and preview the page in your browser. Click the button and you see a pop-up window appear in your browser. The appearance of this window is different depending on which browser you are using.

1607.jpg

Clicking the Submit button triggers the pop-up window.

Now that you have created the pop-up window, you will add more code to populate your prompt window with information, as instructed in the next step.

9 Close your browser and add the following code to your JavaScript variable declaration (added in step 6):

var name=prompt("Please enter your name","Chris P. Bacon");

Save your file and preview it in your browser. Test the page again by pressing Submit. The new values you just added are now visible within the window. You will now add code to your JavaScript to take the value of the text box and write it out onto a new HTML page.

10 Close your browser and add the following code to your JavaScript code:

<script type="text/javascript">

function show_prompt()

{

var name=prompt("Please enter your name","Chris P. Bacon");

if (name!=null && name!="")

{

document.write("Hello " + name + "! How are you today?");

}

}

</script>

This code is composed of two parts: an if statement and a then statement. The if statement looks for a value in the text field; if there is a value, the document.write line is run, and the name value is displayed.

3089.jpg The characters != and && contained in the code (name!=null && name!="") are known as operators in JavaScript and they help build the logic of any given function.

The document.write code is a statement that instructs your web browser to write data on a web page. In this case, the statement writes the text “Hello” plus the content of the prompt window text field, followed by “How are you today?”

11 Save your page, and then preview it in your browser. Leave the default name value in for now and click OK. A new page is built based on the code you added in the previous step. Click the Back button in your web browser, click the Submit button again, and then type your name. Click OK; a new page with the new value is created.

3095.jpg In some browsers (such as Safari) you may be seeing just a blank page. This is due to the way that different browsers handle document.write. If this is case for you, move on to the next step.

1646.jpg

The value from the text field is written on the page.

This is a relatively simple JavaScript function, but it should give you a basic understanding of how JavaScript communicates with the HTML elements on a page, as well as the basic logic of a JavaScript function. In the next exercise, you’ll learn about JavaScript events.

JavaScript events

The JavaScript event you worked with in the previous exercise was an onclick event that triggered the code when you clicked the Submit button. There are other events you can use, and to better understand how these events work, you will modify the current example.

1 In your HTML code, change your onclick event to the onmouseover event (highlighted in red):

<input type="button" onmouseover="show_prompt()" value="Submit" />

2 Save your file and preview it in your browser. Now, place your cursor over the button without clicking; the prompt window appears. The onmouseover event triggers the JavaScript as soon as the cursor enters the area of the button.

1661.jpg

Events are often based on user interaction, such as moving the mouse cursor over an object.

3077.jpg The onmouseout event is closely related to onmouseover except that it triggers the JavaScript when the cursor leaves the area of the button.

Currently, this event is tied to your button, but you can move the event from the button to the actual page.

3 Select the onmouseover event and its value, and then press Ctrl + X (PC) or Command + X (Mac OS) to cut the code. Locate the opening body tag and press Ctrl + V (PC) or Command + V (Mac OS) to paste the code, as shown here:

<body onmouseover="show_prompt()">

A mouseover event on the actual page will work, but best practice is to use the onload event, which triggers your JavaScript as soon as the page is opened:

<body onload="show_prompt()">

4 After changing the event to onload, save your page and preview it in your browser. As soon as your page opens, you trigger the prompt window. You could enter the text here, but as the event is currently structured, it would write the text to the page, so click Cancel.

1702.jpg

The onload event can be useful, but for this example, it would be distracting for the user.

With this exercise, you learned that JavaScript lets you choose where and how you call it. In both cases, user interaction triggers the code, but the onload event gives the user little choice as to when to trigger the code, whereas the onclick event (attached to the button), gives the user more of a choice.

Placing your JavaScript into an external document

You can save JavaScript in an external file that is linked from your HTML pages in much the same way you do with external style sheets. The benefits are the same: to easily update code that’s located in a single file.

1 In your text editor, choose File > New, and then choose File > Save. In the dialog box that appears, save this file in your HTML5_08lessons folder as promptwindow.js. The extension .js is for external JavaScript files. Keep in mind that your text editor may have a separate menu command for creating JavaScript files, in this case, you should choose that option. Additionally, if any text was automatically generated, you should delete it.

2 Return to 08_subscribe_work.html and select the code within the two <script> tags. Do not select the script tags themselves.

3 Press Ctrl + X (PC) or Command + X (Mac OS) to cut this code out of your document. Switch to the promptwindow.js document and press Ctrl + V (PC) or Command + V (Mac OS). Save this file.

4 Switch back to your HTML page, and add the following code (highlighted in red) to your opening <script> tag:

<script type="text/javascript" src="promptwindow.js">

</script>

5 Save your page and then preview it in your browser. The script works as it did before.

6 Close your browser, and then close your HTML and JavaScript documents since you will be working with new files in the next exercise.

3066.jpg If your script is not working, check to make sure you spelled the name of the JavaScript file correctly. Also, check to make sure that the JavaScript file is on the same level as your HTML file within your root folder.

There are multiple benefits to saving your JavaScript in an external file. Some of these benefits are:

  • The ability to place multiple functions within a single document (although inline JavaScript has this benefit as well).
  • Having a single reference for your JavaScript makes it easier for debugging purposes.
  • The external JavaScript file can be cached by the web browser, thus preventing the need to reload the script on new pages.

The Document Object Model

JavaScript has access to objects within a browser; this is how the pop-up window from your previous exercise appeared on screen. This access takes advantage of the Document Object Model (DOM), which is a convention for accessing data within HTML pages. This model describes how all elements in an HTML page, such as forms and images, are related to the topmost structure, known as the document.

JavaScript has access to the document and the related elements on your page in a way that HTML does not. This access allows JavaScript to:

  • Validate form fields
  • Detect the browser being used
  • Respond to user events
  • Store and retrieve information on a user’s computer

Recall the first exercise and the section of code you added labeled document.write (the seventh line from the top).

<script type="text/javascript">

function show_prompt()

{

var name=prompt("Please enter your name","Chris P. Bacon");

if (name!=null && name!="")

{

document.write("Hello " + name + "! How are you today?");

}

}

</script>

This section of code is referred to as a function. The behavior demonstrated on your page is one of the simplest examples in JavaScript because there are very few objects in the document. Most HTML documents have multiple objects, and it is possible to pass a text value to another part of the page, or to submit it via a form.

JavaScript frameworks

Imagine the following scenario: A designer is starting a new project and her client is interested in adding an interactive photo gallery to the site. The designer also needs to create a form that requires JavaScript validation. Since the designer is new to JavaScript, she finds code she can use for the photo gallery and the form validation, and adds it to her page. The designer later gets another job similar to the first, and she decides to reuse the code from her first project, so she saves the JavaScript code into an external file.

The designer now has a reusable library of code she can add to future projects, but there are some potential problems with this approach:

  • The designer needs to organize, maintain, and update her library.
  • The code the designer found could be poorly written.
  • Poorly written JavaScript can slow down the performance of a website and/or cause security issues. Unless the designer is an expert at optimizing code, she may be unknowingly distributing bad code.

JavaScript frameworks are a better solution. There are several professionally written libraries available for use by designers. These libraries are large collections of functions built and tested by other designers and developers to form a common library. These collections of functions are available for immediate use, so if a designer needs to add an accordion menu (a menu that collapses and expands based on user events), he or she might readily find the code they need.

You will now use jQuery, one of the most popular and accessible JavaScript frameworks for designers. jQuery is useful for designers because it uses CSS syntax to search and access the page, thereby decreasing the amount of scripting language you need to learn.

Hiding an element with jQuery

In this exercise, you’ll create an expandable container the user can toggle open and closed. The figures below show jQuery’s animation features. The first image contains a box in its initial view; readers interested in the calorie content of the smoothie can click the See calories link to expand this section. The second image shows the expanded box after the user has clicked the button.

17451.jpg 1752.jpg

An example of the collapsible box you will create.

As you will see, jQuery lets you experiment with different methods of expanding the box and with the timing. The collapsible box will take two exercises to complete; in this first exercise, you will hide the section.

1 Perform this step to see the code of the jQuery framework. If you’d prefer to not see this, move on to step 2. Choose File > Open. In the dialog box that appears, navigate to your HTML5_08lessons and open the jquery.js file. Scroll to see the functions contained within the file. This file is well commented, so you can get a sense of what the functions do. When you are finished, close the file without saving it.

1767.jpg

You can reference the functions in the jQuery document in your web page, but you rarely need to modify them.

2 Open the document jquerytoggle.html located in your HTML5_08lessons folder. Preview this page in your browser. The section of the page you will hide is the list below the heading Calories per serving. Close your browser and return to your document. Scroll to locate the HTML for this section; the list is wrapped in a div tag with the ID CalorieBox. This is the div you will hide.

3 In the jquerytoggle.html page, add the link to the jQuery JavaScript file, which is located in your HTML5_08lessons folder.

In the head section, immediately below the closing </style> tag, add the following code:

<script type="text/javascript" src="jquery.js"></script>

Choose File > Save. Your document can now access the functionality within the library. Note that this link to the jQuery library should go on every page that might reference code within it. Now you will add another script tag to add code that hides your Calories box.

4 Immediately below the <script> tag you just added, type the following code to add an empty <script> element:

<script type="text/javascript" src="jquery.js"></script>

<script>

</script>

You will now add a line of code that is included in almost every project that uses jQuery.

5 Add the following code into your empty <script> element:

<script>

$(document).ready(function() {

});

</script>

In this code, the $ symbol is a reference to the jQuery object and ready is the event to respond to (in this case, the document being ready). In addition, you are defining a new function with function. This section of code is referred to as a ready function and prevents your code from searching the DOM until the document is fully loaded.

For example, in the following code, you will hide text on your page, so you want this code to be hidden when the page first loads.

6 Scroll to locate the HTML code close to the bottom of the page that begins with the line <div id="CalorieBox">. This is the element on the page that you will hide; it contains a definition list that has the calorie values. jQuery allows objects in the DOM to be selected by several criteria. Since you want to select one specific element, you will search for that specific ID.

7 Scroll back up the page and add the following code immediately below your document.ready function:

$(document).ready(function() {

$('#CalorieBox').hide();

});

The hash tag (#) tells jQuery to search for an element with the ID 'CalorieBox' (using the CSS selector syntax). Once found, jQuery will run the selected element’s hide function, which is also a jQuery function.

8 Save your page, and then preview it in your browser. Your Calories section has disappeared from the page. Note that all the functionality for this effect is condensed in the line you added in the last step. This line works because the jQuery library is referenced in your HTML page.

17861.jpg 1792.jpg

The CalorieBox before hiding it with jQuery.

The CalorieBox after hiding it with jQuery.

This page lacks a trigger to cause the box to appear. You will now add this trigger by adding a link to the Calories per serving heading, as well as more jQuery code.

Adding an event to trigger the show effect

The effect you want to create is to expand the list currently hidden when the user clicks the Calories per serving heading. To do this, you will make the heading a link and give it an ID.

1 Locate the Calories per serving heading and add the following attributes:

<h4><a id="triggerCalorieBox" href="#">Calories per serving</a></h4>

You are giving this heading an ID so you can target it with another line of jQuery. The href attribute is a dummy link that makes the heading a hyperlink, but is only there to serve as a trigger.

2 Scroll to your JavaScript code and add these four lines:

$(document).ready(function() {

$('#CalorieBox').hide();

$('a#triggerCalorieBox').click(function() {

$('#CalorieBox').show();

e.preventDefault()

});

});

The first line identifies the hyperlinked ID you created in step 1 and attaches it to a click event. The second line is the instruction to show the CalorieBox ID. The third line is needed to override the default behavior of the hyperlink. (As previously noted, this hyperlink doesn’t go to another page, so this line is necessary.) The fourth line is the closing bracket for the new function. (The opening bracket for this function is on the .click(function() line.)

3 Save your page and then preview it in your browser. Click the Calories per serving link; the box expands. The style for this box has been defined as 450 pixels wide with a black border on all sides.

1814.jpg

Clicking the link triggers the box to expand.

4 To enable the box to close again upon clicking, you need to add a line of code to hide the box after it has been expanded. The effect you want is for the user to toggle the box open and close by clicking the link. jQuery has a toggle effect you can use. You simply need to replace the show effect you have with the toggle. Replace the show effect with the following code:

$('a#triggerCalorieBox').click(function() {

$('#CalorieBox').toggle();

e.preventDefault();

5 Save your page and preview it in your browser. The CalorieBox is still hidden when the page loads. When you click it, it expands, and when you click again, it collapses. Close your browser and return to your text editor.

1834.jpg

Using the toggle effect, the user can now open and close the box.

To make the show-and-hide effect more interesting, you will use the animation capabilities of jQuery.

6 In the lines of code you have already written, you can add control for the speed of the show-and-hide effect. Add the following code:

$('#CalorieBox').toggle('slow');

Save your page and then preview it in your browser. Clicking the link now results in a slow expansion of the box. If you want more precise control of the speed of the effect, jQuery allows you to control the speed using millisecond number values.

7 Return to your text editor and replace the 'slow' value with a millisecond value (be sure to remove the single quotation marks, which are used for keywords such as 'slow' or 'fast'):

$('#CalorieBox').toggle(1200);

The 1200 milliseconds value is equivalent to 1.2 seconds. Save your page and then preview it in your browser. Clicking the link now results in a much slower expansion of the box. You’ll now increase the speed of this effect.

8 Return to your text editor and replace the 1200 value with 500, the equivalent of one-half second:

$('#CalorieBox').toggle(500);

You also have options to change the behavior of the box: in addition to .show, .hide, and .toggle, there are effects such as .slideDown, .fadeIn, and .fadeOut. You’ll change your toggle effect to the slideToggle effect.

9 Add the following code:

$('#CalorieBox').slideToggle(500);

Save your page and preview it in your browser. When satisfied, close your browser and your file since you will be working with a new document in the next exercise.

18551.jpg

The slideToggle effect changes the behavior of the animation.

As you can see, jQuery allows different options for your designs. The ability to show and hide animated elements is just one thing you can do with this library. The best way to learn more about jQuery is to go online to the source at jQuery.com, or to explore other online resources.

Self study

1 Experiment with different effects for your jQuery calorie box. For example, replace the .slideToggle effect in the jquerytoggle.html page with the .fadeIn effect.

2 Experiment with the speed values in your code (currently set to 500 milliseconds) to see how they affect the behavior of the element.

3 Browse jquery.com, use the online interactive tutorials, and choose an example to integrate into your page.

Review

Questions

1 What is an event as it relates to JavaScript and HTML?

2 What is a JavaScript library, and what are the advantages of using one?

3 In this line of code, what does the number 500 stand for?

$('#CalorieBox').toggle(500);

Answers

1 An event on an HTML page often originates from a user interaction, such as clicking a button or loading a page. These events can then trigger specific JavaScript code that runs in the user’s browser.

2 A JavaScript library, such as jQuery, is a collection of JavaScript code that lives inside an external JavaScript file. You can easily reference a library to add functionality, such as animated menus or user interface elements. Using a library is advantageous for designers because they can add relatively sophisticated behavior without writing complex JavaScript code.

3 Milliseconds.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.124.65