CSCI 102T

The Socio-Techno Web

Home | Schedule | Labs | CS@Williams

Lab 7: More Javascript and jQuery

For this week's lab assignment, you will learn more about using JavaScript and jQuery to add intelligence and advanced functionality to your web pages. Specifically, you will learn about using Javascript with HTML forms, in addition to rotating images, fading in, and dragging objects using jQuery.

Exercise 1: Mad Libs with HTML Forms

Recall your Mad Lib webpage from last week. Requiring your friends to respond to a bunch of prompts (as in Lab 6) is fine, but it can be tedious, and it does not allow them to go back and change a previous response. In order to support this functionality, you can use an HTML form with a series of input fields. In this exercise, you will create a modified version of your madlib.html page that creates the same story using an HTML form instead of Javascript prompts.

In order to support forms (i.e., text fields with an input button), you need to add HTML to create the text fields and button, and then a JavaScript function to manipulate the input text and write the story. I recommend that you read through this entire exercise before typing anything.

  1. Start by creating a copy of your madlib.html and save the file as madlib-form.html in your repository. You will eventually remove the code that you wrote last week. The good news is that much of your Javascript code for printing the story will remain the same. However, rather than using a bunch of prompts to get the input, you will use an HTML form and button. Check out this page for more info on using forms and Javascript.
  2. First add an HTML form and a button to the body of your webpage. Notice how the button wants to run "submitName()" when it is clicked. This means that the browser will try to call a Javascript function called submitName() when the button is clicked and the form is submitted.
    <form name="myForm" >
      First name: <input type="text" name="fname">
      Last name: <input type="text" name="lname">
    </form>
    
    <button onclick="submitName()">Submit</button>
    	
  3. You also need a place to write the output, i.e., your final story. To do this, we'll create an empty paragraph in our HTML body and assign it an "id." We will later use JavaScript to fill in the paragraph.
    <p id="result"></p>
    	
  4. Next, create your submitName function in the head of your document (within the <script> tags as always) that will process the data. Notice the correlation between myForm, fname, lname, and result in the HTML and Javascript. Spend a few moments studying this and make sure you understand what's going on before trying the next step.
    function submitName() {
      	var first=document.forms["myForm"]["fname"].value;
      	var last=document.forms["myForm"]["lname"].value;
      	result.innerHTML = first+" "+last+" is a great person.";
     }
    	
    Note from lab: Your final story output (result.innerHTML = ...) will end up being a very long line of code. You can insert line breaks, however, you have to use the "\" character inside of quoted text in JavaScript. For example:
    result.innerHTML = first+" "+last+" is a great person. This is a really long line of code.";
    	 
    can be rewritten as
    result.innerHTML = first+" "+last+" is a great \
    person. This is a really long line of code.";
    	 
  5. Using this as a template, modify your Mad Libs code to accept input via an HTML form instead of using Javascript prompts. Save your file often and test regularly!
  6. See a (very boring) working example: madlib-form.html

Exercise 2: Hide and Fade

  1. Now we will look at an example that uses jQuery. jQuery is a JavaScript library that gives developers extra functions for adding advanced features to web pages. Libraries, in general, are designed to make it easy for developers to do something that is normally quite difficult. We are going to use an external jQuery library that defines two useful functions: hide() and fadeIn(). To get started, download the file fadeIn.html to your repository as we did last week, and open it in Atom.
  2. Click in the blank line between <link> and the closing </head> tags near the top of the page, and type:
    <script src="http://www.cs.williams.edu/~cs102/assignments+labs/jquery/jquery-1.11.3.min.js"></script>
    
    This code links a file named jquery-1.11.3.min.js to your web page. When the browser loads your fadeIn.html web page, it also downloads jquery-1.11.3.min.js (a JavaScript file) and runs the code inside it.
  3. Press the Return key once more, and type:
    <script>
    $(document).ready(function() {
        $('body').hide().fadeIn(3000);
    });
    </script>
    
  4. Save the file and view it in a web browser. You should see the page fade slowly into view. Change the value of 3000 to different values (between 250 and 10000) and see how that changes the way the page works.
  5. Now go back and look at the code you typed. Can you figure out what is happening? The syntax is tricky. Hint: The document.ready line takes advantage of the programming in the jQuery library to tell the browser to execute the next line of code at the right time. The hide().fadeIn() line does something magical: it makes the page contents disappear and then slowly fade into view over the course of 3000 milliseconds. Notice how the seemingly crazy punctuation follows the same nesting rules as your HTML code. You always "close" curly braces and parentheses in the reverse order in which you open them. Indenting is optional, but highly recommended. It will helps make your code more readable.
  6. Experiment a bit with the hide() and fadeIn() functions until you fully understand what's going on in this example.
  7. See a working version here: fadeIn.html.

Exercise 3: Spinning Images

To rotate images using jQuery, we will use another jQuery library called JQueryRotate.

  1. For this exercise, make a new webpage called spin.html in your repository. Write your initial tags (html, head, title, body) along with their closing tags as you have done on previous pages. You may want to link to your CSS file again for consistent formatting.
  2. To make use of the new jQuery library in addition to the standard one, you need to add the following lines to the head of your document:
    <script src="http://www.cs.williams.edu/~cs102/assignments+labs/jquery/jquery-1.11.3.min.js"></script>
    <script src="http://www.cs.williams.edu/~cs102/assignments+labs/jquery/jQueryRotate.2.3.js"></script>
    
  3. You can use the library in a number of ways. To rotate an image (without making it spin), you must first add an "id" attribute to the img tag that you want to manipulate. Add an image to the body of your webpage and add "id=img" as an attribute to the img tag (just as many of you have done with "width" or "height" attributes in the past). You can use whatever image you want for this example, but a smaller image is probably best. Note that the name you use for id is not important, just like variable names. You just have to be consistent.
  4. Then, define your document.ready function in the head within a script tag as we did in Exercise 2 above. (If you forgot how to do this, look at your fadeIn.html example.) Within document.ready, type:
    $("#img").rotate(45);
    or
    $("#img").rotate({angle:45});
    to rotate the image 45 degrees clockwise. Try it and make sure it works.

    You can also rotate the image endlessly by adding this to your document.ready function:
    var angle = 0;
    setInterval(function(){
      angle+=3;
      $("#img").rotate(angle);
    },50);
    	
  5. Play around with this some more. Make sure you understand the code. There are a few more fun examples of things you can do with this jQuery library on this page. Try a few!
  6. See a working example: spin.html

Exercise 4: Trick or Treat!

In this week's last exercise, you will learn about the Draggable widget in jQuery. You will create a webpage that allows you to decorate a pumpkin or snowman by dragging eyes, a nose, etc to the correct place.

Before making your pumpkin or snowman, let's first look at a simple example that illustrates how the drag functionality works with jQuery. We will use the Draggable jQuery widget for enabling dragging on our webpage. The Draggable widget is very useful. Note: There is another widget (Droppable) which must be used if you want to both drag and drop. More information (including a really cool card game tutorial) can be found here.

Start by downloading smiley.html by Ctrl+clicking and saving the file in your repository. You'll also need the image files. Download smiley-imgs.zip to your repository directory. Double-click on the zip file to uncompress the images into their own folder. You should still be in your repository directory. Open smiley.html in a browser and see how it works.

Now let's look at the code. Open smiley.html in Atom. Look over the code and try to understand what's going on. Starting from the top, I will explain each part of this file.

First, we declare the appropriate headers, including any CSS stylesheets and jQuery libraries. We are using two jQuery libraries in this example.
	
<!DOCTYPE html>
<html>
  <head>
   <link rel="stylesheet" href="http://www.cs.williams.edu/~cs102/cs102t.css" type="text/css">
   <meta http-equiv="content-type" content="text/html; charset=UTF-8">
   <title>Smiley</title>

   <script src="http://www.cs.williams.edu/~cs102/assignments+labs/jquery/jquery-1.11.3.min.js"></script>
   <script src="http://www.cs.williams.edu/~cs102/assignments+labs/jquery/jquery-ui-1.11.4/jquery-ui.min.js"></script>
Next we define our style using standard CSS. We could specify this in a separate file, but since there isn't much styling on this simple page, we can just as easily leave it here in the header.
    <style>
	body {
  	  position: relative;
  	  margin-top: 10px;
  	  background: white;
  	  width: 850px;
  	  color: black;
	}
	   
	h1 {
	  margin-left:auto;
	  margin-right:auto;
	  text-align: center;
	}
    
The next part (still part of our CSS style) defines our background image, which in this case is a yellow circle. IMPORTANT: We specify this image separately so that we can't drag it around the page like the rest of our images.
	#face {
 	  background:url("smiley-imgs/yellow-circle.png");
  	  width: 300px;
  	  height: 300px;
  	  margin-left:0px;
	  margin-right:auto;
	}
    </style>
Now we define the function that actually makes our images draggable. This function gets called as soon as the webpage is loaded in the browser. Using the jQuery function called draggable(), we set all img objects in our webpage to be draggable.

    <script>
	  $(document).ready(function() {
		  $( "img" ).draggable();
	  });
    </script>
  </head>
Finally, we define the HTML. This includes specifying the #face identifier from above (which includes our background image), as well as the rest of our face parts.
  
  <body>  
    <h1>Say Cheese!</h1>

    <table>
        <tr align="center">
            <td width="10%">
                <div id="face"></div>
            </td>
            <td>
                <img src="smiley-imgs/mouth.png"><br><br>
                <img src="smiley-imgs/eyes.png">
            </td> 
        </tr>
    </table>
  </body>
</html>

Your task is to create a page that is similar to smiley.html (call it jack.html, snowman.html, or olaf.html) that allows someone to decorate their own jack-o-lantern, snowman, or Olaf. I have gathered a bunch of snowman images for you to use from this website. I found some pumpkin ones, too, mostly from here. I collected some really awesome Olaf images from here, complete with Halloween accessories! You may use other ones as well. Just make sure you find or create images with a transparent background.

  1. Start by downloading one set of the following files: You only need to make one of these three pages for full credit. Save both files (the zip file and the html file) to your repository.
  2. Double-click on .zip files to uncompress the images. You will want to open the imgs folder that is created to see what files are available for you to use. You may have to alter the sizes using the "width" and "height" attributes of your img tags.
  3. To give you an idea as to what your final page should look like, check out these screenshots:

    screenshot   screenshot
    screenshot   screenshot
    screenshot   screenshot
    You do not have to make them look exactly like this. These are only samples.
  4. It's fairly easy to add audio and video features to your pages. A quick search turned up two good references: here and here. Note that you don't need jQuery for playing audio files; HTML and Javascript is enough. For those of you who like to go above and beyond, here are two mp3 files: halloween_midnight.mp3 and frozen.mp3.
  5. As always, be creative and have fun!

Tasks for lab

  1. Complete Exercises 1, 2, 3, and 4. In the end, you should have completed versions of madlib-form.html, fadeIn.html, spin.html, and either jack.html, snowman.html, or olaf.html.
  2. Save your files and test often! If you finish everything and still want to do more, try combining tricks. Can you make your pumpkin rotate on mouse click? (I haven't tried this, but I bet it's possible!)



HTML Validator