Difference between revisions of "Introduction to JavaScript Fall 2010"

esse quam videri
Jump to: navigation, search
m (Class Schedule)
Line 1: Line 1:
 
== Introduction ==
 
== Introduction ==
  
JavaScript is a scrappy little language that has seen a lot of changes since its introduction in 1995. Though the language has often been abused, there has been a resurgence of interest since the introduction of highly dynamic web applications like Gmail and Google Maps, which take full of advantage of JavaScript's capabilities.
+
This week, I want to introduce you to the concept of JavaScript timers. Timers can be used to delay a function before it gets called or to repeatedly call a function over a period of time. I also want to discuss '''anonymous functions''', which will be useful when we start using timers.
  
This class will treat JavaScript with the respect that it deserves. Instead of relying on poorly designed tools to generate half-baked JavaScript, we will be hand writing clean and compact JavaScript.
+
== Anonymous Functions ==
  
I fully expect that this class will include students with little to no experience with programming or JavaScript. Luckily, JavaScript is a simple language to work with. Unlike many other languages, JavaScript doesn't require any fancy development environments or expensive tools. I hope that everyone will come away from this class knowing a lot more about JavaScript than they did before starting.
+
'''Anonymous functions''' are functions that don't have names. Although you might not realize it, you've already used anonymous functions in this class. This is what an anonymous function looks like:
  
== Who's teaching this class? ==
+
  function() {
 +
    // your code here
 +
  }
  
My name is [http://www.mattephraim.com Matt Ephraim]. I am a web developer at [http://metromix.com Metromix] and I'm currently working on a Master's degree in Information Architecture at [http://www.iit.edu IIT].
+
Notice that the function doesn't have a name attached to it. In this class, we have been creating anonymous functions and then storing them on an object like this:
  
You can contact me at [mailto:mephraim@colum.edu mephraim@colum.edu].
+
  Behavior.someFunction = '''function() {
 +
    // your code here
 +
  };'''
  
I won't have any office hours on campus, but if you would like to meet with me, I am available most days after 5pm and always available after class.
+
Anonymous functions don't need to be stored in a variable or on an object. You can also pass anonymous functions around as parameters. For example, you could pass
 +
an anonymous function as a parameter to the jQuery ''click'' function:
  
== Tools for this class ==
+
  $("#button-id").click(function() {
 +
    // code for handling the click event
 +
  });
  
This is a list of tools that will come in handy for JavaScript development. I will update this list as the class goes on.
+
The anonymous function will work exactly the same way this code:
  
=== Text Editors ===
+
  $("#button-id").click(handleClick);
 +
 
 +
  function handleClick() {
 +
    // code for handling the click event
 +
  }
  
'''For Windows'''
+
The only difference is that, in the first example, we didn't give a name to the handleClick function. We just created it as an anonymous function and passed it in
* [http://notepad-plus.sourceforge.net/uk/site.htm Notepad++] (free)
+
to the click function.
* [http://www.e-texteditor.com/ e TextEditor]
 
* [http://www.scintilla.org/SciTEDownload.html SciTE] (free and open source)
 
  
'''For OS X'''
+
Anonymous functions will become more useful when we start working with timers.
* [http://www.barebones.com/products/TextWrangler/download.html TextWrangler] (free)
 
* [http://macromates.com/ TextMate]
 
* [http://www.panic.com/coda/ Coda]
 
  
=== Browser Tools ===
+
== JavaScript Timers ==
  
'''Tools for Firefox'''
+
Sometimes, you don't want run a function right away. Instead, you want the function to run after a delay.
* [http://getfirebug.com/ Firebug]
+
Other times, you want JavaScript to handle running the function repeatedly at a set interval. JavaScript timers allow you do both.
* [https://addons.mozilla.org/en-US/firefox/addon/60 Web Developer Toolbar]
 
  
=== Books ===
+
=== Using a Timer to Delay a Function Call ===
  
I won't be teaching directly out of a book for this class, but there are a few books that will come in handy:
+
The first type of timer uses the '''setTimeout''' function. The '''setTimeout''' function takes in a function name or an anonymous function as its first parameter and the number of milliseconds you'd like to delay before calling the function as the second parameter. For example, lets say you have a button that, when clicked, adds a new paragraph to a div called ''myDiv''. You could handle it with jQuery like this:
  
[http://www.amazon.com/JavaScript-Definitive-Guide-David-Flanagan/dp/0596101996/ JavaScript: the Definitive Guide]: this is, essentially, the JavaScript Bible. If you want to know where much of the content of this course comes from, look no further than this book. I highly recommend buying it. And make sure to get the latest edition (currently, the 5th is the latest).
+
  $('#button-id').click(addParagraph);
 +
 
 +
  function addParagraph() {
 +
      $('#myDiv').append('<p>hello</p>');
 +
  }
  
[http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ JavaScript: the Good Parts]: this is a brief and opinionated book, but if you're already somewhat familiar with JavaScript, it makes a good reference. It's no substitute for the Definitive Guide, but it contains some good information.
+
You should already be familiar with this kind of thing, because we've done it in class.
  
== Resources ==
+
However, let's say that you didn't want to add the element to the page right away. Instead, you wanted to add the element after waiting for 2 seconds. You can use the '''setTimeout''' function to accomplish this.
  
This is a list of resources that will come in handy for this class.
+
  // When the button is clicked, create a new timer that will call the
 +
  // addParagraph function after 2 seconds
 +
  $('#button-id').click(function) {
 +
      '''setTimeout(addParagraph, 2000);'''
 +
  };
 +
 
 +
  function addParagraph() {
 +
      $('#myDiv').append('<p>hello</p>');
 +
  }
  
* [http://www.w3schools.com/js/default.asp W3Schools JavaScript reference]
+
The setTimeout function above will delay the call to addParagraph for 2000 milliseconds, which is the same as 2 seconds. '''setTimeout''' will take in the name of a function as the first parameter:
* [https://developer.mozilla.org/en/JavaScript Mozilla JavaScript reference]
 
* [http://diveintohtml5.org/ Dive Into HTML5 (an online book about HTML5)]
 
  
== Interesting JavaScript Websites ==
+
  // Call '''functionName''' after 1 second
 +
  setTimeout('''functionName''', 1000);
  
Each week, I will show you an interesting example of JavaScript usage in the wild. You can find a list of all of the websites here.
+
Or it will take in an anonymous function that you want to be called:
  
* [http://www.chromeexperiments.com/ Google's Chrome Experiments / Chrome Showcase]
+
  // Call the function block after 1 second
* [http://www.beautyoftheweb.com/ Microsoft's Beauty of the Web / IE9 Showcase]
+
  setTimeout('''function() {'''
 +
      // some code you want to be called
 +
  }, 1000);
  
== Class Schedule ==
+
In both of these examples the functions will be called after 1000 milliseconds (remember, there are 1000 milliseconds in 1 second).
  
* Class 1 (9/7/2010): [[Introduction_to_JavaScript_Fall_2010_Class_1|Introduction]]
+
=== Using a Timer to Repeatedly Call a Function ===
* Class 2 (9/14/2010): [[Introduction_to_JavaScript_Fall_2010_Class_2|Javascript Basics Part 1]]
 
* Class 3 (9/21/2010): [[Introduction_to_JavaScript_Fall_2010_Class_3|Javascript Basics Part 2]]
 
* Class 4 (9/28/2010): [[Introduction_to_JavaScript_Fall_2010_Class_4|Javascript Events]]
 
* Class 5 (10/5/2010): [[Introduction_to_JavaScript_Fall_2010_Class_5|Introduction to jQuery]]
 
* Class 6 (10/12/2010): [[Introduction_to_JavaScript_Fall_2010_Class_6|JavaScript Objects]]
 
* Class 7 (10/19/2010): [[Introduction_to_JavaScript_Fall_2010_Class_7|Forms and More jQuery]]
 
* Class 8 (10/26/2010): [[Introduction_to_JavaScript_Fall_2010_Class_8|Arrays]]
 
* Class 9 (11/2/2010): [[Introduction_to_JavaScript_Fall_2010_Class_9|Raphaël]]
 
  
 +
The second type of timer uses the '''setInterval''' function. Like the '''setTimeout''' function, the '''setInterval''' function takes in a function name or an anonymous function block as its first parameter and a number in milliseconds as the second parameter:
  
 +
  // Call '''myFunction''' every second
 +
  setInterval('''myFunction''', 1000);
  
 +
Or:
  
<p></p>
+
  // Call the function block every second
[[Category:Introduction to JavaScript Fall 2010]]
+
  setInterval('''function() {
 +
      // some code you want to  be called
 +
  }, 1000);
 +
 
 +
What makes '''setInterval''' different is that it will repeatedly call the function, with a delay of milliseconds between each function call. In the examples above, the function will be called every 1000 milliseconds.
 +
 
 +
== Stopping Timers ==
 +
 
 +
Both '''setTimeout''' and '''setInterval''' are functions that will wait a number of milliseconds before calling another function. What if you called '''setTimeout''' or '''setInterval''', but then decided that you didn't want them to call the other function after all. How would you stop the function call from happening?
 +
 
 +
=== Stopping setTimeout ===
 +
 
 +
When you call the '''setTimeout''' function it returns a value you can store in a variable:
 +
 
 +
  var timer = setTimeout(functionName, 1000);
 +
 
 +
If you have stored '''setTimeout's''' return value you can use that value with another function called '''clearTimeout'''. The '''clearTimeout''' function will stop the timer from running if it hasn't already run yet.
 +
 
 +
For example, if I set a timer for 10,000 milliseconds (10 seconds), I can stop the timer before it runs and it will never call the function, even if 10 seconds goes by:
 +
 
 +
  // Create a new timer and store it in the ''timer'' variable
 +
  var timer = setTimeout(myFunction, 10000);
 +
 
 +
  ... // whatever other code you might want to go here
 +
 
 +
  // If 10 seconds haven't passed already this will cancel the timer
 +
  // and the function will never get called
 +
  clearTimeout(timer);
 +
 
 +
In the example above, '''setTimeout''' creates a new timer, which gets stored in the '''timer''' variable. Later on in the code '''clearTimeout''' stops the timer from running. If 10 seconds already have gone by, '''clearTimeout''' won't do anything.
 +
 
 +
=== Stopping setInterval ===
 +
 
 +
Just like the '''setTimeout''' function, '''setInterval''' returns a timer that you can store in a variable:
 +
 
 +
  var timer = setInterval(functionName, 1000);
 +
 
 +
Once you have the timer that '''setInterval''' returned, you can use the '''clearInterval''' function to stop the timer from running. '''clearInterval''' takes in a timer variable and cancels the timer:
 +
 
 +
  // Create a new timer and store it in the '''timer''' variable
 +
  var timer = setInterval(myFunction, 10000);
 +
 
 +
  ... // whatever other code you might want to go here
 +
 
 +
  // Stop the timer from running. This will prevent the
 +
  // timer from calling the function again
 +
  clearInterval(timer);
 +
 
 +
The '''clearInterval''' function will take the timer that his been running and stop it from running again. '''setInteval''' repeatedly calls a function until '''clearInterval''' stops it from running again.
 +
 
 +
== Activity ==
 +
 
 +
From this class, we will be using a template to build 2 timers. One that increments a number in a box, and one that creates a simple clock that counts up to 60 seconds and then resets itself.
 +
 
 +
You can download the template for the activity [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/counter.zip here].
 +
 
 +
<!--
 +
The completed version is [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/counter_complete.zip here].
 +
-->
 +
 
 +
== Assignment 5 ==
 +
 
 +
'''Due Friday November 19th'''
 +
 
 +
Your assignment this week is to create an animation that uses a timer to draw elements on the canvas. You can choose to draw any animation you want as long as it fulfills the following criteria:
 +
* It must use a timer to draw elements on the canvas, or to interact with elements on the canvas using either '''setTimeout''' or '''setInterval'''
 +
* It must draw multiple elements to the canvas. These can be circles, rectangles or whatever other shape is supported by Raphael.
 +
* Draw as many elements as you want, but draw at least 3 elements.
 +
* The elements must respond to a mouse event. The mouse event can be a click, a mouseover, mouseout or whatever other events are supported by Raphael.
 +
* The elements must change in some way in response to the mouse event. Remember that you can use the '''attr''' or '''animate''' functions to change the attributes on any Raphael element.
 +
 
 +
The rest of the animation is up to you. Remember that you can change the x and y position of an element using 'x' and 'y' (or 'cx' and 'cy' for circles) with the '''attr'''
 +
or '''animation''' functions:
 +
 
 +
  var circle = canvas.circle(5, 5, 10);
 +
 
 +
  // animate the circle to position x = 20, and y = 30
 +
  circle.animate({ cx: 20, cy: 30 }, 200);
 +
 
 +
  var rect = canvas.circle(100, 100, 10, 10);
 +
 
 +
  // animate the rect to position x = 50, and y = 20
 +
  circle.animate({ x: 50, y: 20 }, 500);
 +
 
 +
A list of other attributes you can modify is [http://raphaeljs.com/reference.html#attr here].
 +
 
 +
Also remember that you can attach mouse events to Raphael elements in the same way that you can attach events with jQuery:
 +
 
 +
  var circle = canvas.circle(5, 5, 10);
 +
 
 +
  // change the color of the element when the user clicks on it
 +
  circle.click(function() {
 +
      circle.animate({ fill: '#6DBE9F' });
 +
  });
 +
 
 +
Remember that you can find documentation and examples at the [http://raphaeljs.com/reference.html Raphael site], and you can use the [[Introduction_to_JavaScript_Fall_2010_Class_10|Raphaël]] page from last week to see how to draw Raphaël elements.
 +
 
 +
You can also see a list of jQuery's event handlers [http://docs.jquery.com/Events here] under '''Event helpers'''. Many of jQuery's helpers have the same names as Raphael's event helpers.
 +
 
 +
I have posted a sample project that shows you the kind of thing I'm looking for [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/circles.zip here]. You can use it as a starting point if you'd like.
 +
 
 +
If you have any questions about the assignment let me know.
 +
 
 +
== Final Project ==
 +
 
 +
We've covered a lot of topics in the class. I'd like you to create final project
 +
that incorporates '''at least 4''' of the topics listed below.
 +
 
 +
'''The project is up to you'''. If you have a project for '''another class''' or something at '''work'''
 +
that could be made better using JavaScript, you are welcome to use it. If you have a '''personal
 +
portfolio''' that you'd like to make more exciting with JavaScript, that works too. You can also
 +
create a simple '''art''' project or '''game'''.
 +
 
 +
I'd like you to email your project idea before next week's class. If you are having a hard time
 +
coming up with a project, let me know and I can help you figure out something else.
 +
 
 +
The import thing is: '''don't panic'''. I'm not expecting anyone to become a JavaScript genius
 +
in this class. Your project can be simple. Just make sure to include '''at least 4''' of the topics
 +
listed below.
 +
 
 +
Your final project will be due Friday December 10th, and you will present your project in class
 +
on December 13th.
 +
 
 +
'''Topics'''
 +
 
 +
* [[Introduction_to_JavaScript_Fall_2010_Class_3|if and else (control flow)]]
 +
* [[Introduction_to_JavaScript_Fall_2010_Class_3|Loops]]
 +
* [[Introduction_to_JavaScript_Fall_2010_Class_5|jQuery]]
 +
* [[Introduction_to_JavaScript_Fall_2010_Class_5|jQuery event handling]]
 +
* [[Introduction_to_JavaScript_Fall_2010_Class_5|Changing styles]]
 +
* [[Introduction_to_JavaScript_Fall_2010_Class_6|Objects]]
 +
* [[Introduction_to_JavaScript_Fall_2010_Class_6|Storing your code with objects]]
 +
* [[Introduction_to_JavaScript_Fall_2010_Class_7|Reading forms]]
 +
* [[Introduction_to_JavaScript_Fall_2010_Class_8|Arrays]]
 +
* [[Introduction_to_JavaScript_Fall_2010_Class_9|JavaScript art with Raphaël]]
 +
* [[Introduction_to_JavaScript_Fall_2010_Class_10|Timers]]

Revision as of 00:17, 10 November 2010

Introduction

This week, I want to introduce you to the concept of JavaScript timers. Timers can be used to delay a function before it gets called or to repeatedly call a function over a period of time. I also want to discuss anonymous functions, which will be useful when we start using timers.

Anonymous Functions

Anonymous functions are functions that don't have names. Although you might not realize it, you've already used anonymous functions in this class. This is what an anonymous function looks like:

 function() {
   // your code here
 }

Notice that the function doesn't have a name attached to it. In this class, we have been creating anonymous functions and then storing them on an object like this:

 Behavior.someFunction = function() {
   // your code here
 };

Anonymous functions don't need to be stored in a variable or on an object. You can also pass anonymous functions around as parameters. For example, you could pass an anonymous function as a parameter to the jQuery click function:

 $("#button-id").click(function() {
   // code for handling the click event
 });

The anonymous function will work exactly the same way this code:

 $("#button-id").click(handleClick);
 
 function handleClick() {
   // code for handling the click event
 }

The only difference is that, in the first example, we didn't give a name to the handleClick function. We just created it as an anonymous function and passed it in to the click function.

Anonymous functions will become more useful when we start working with timers.

JavaScript Timers

Sometimes, you don't want run a function right away. Instead, you want the function to run after a delay. Other times, you want JavaScript to handle running the function repeatedly at a set interval. JavaScript timers allow you do both.

Using a Timer to Delay a Function Call

The first type of timer uses the setTimeout function. The setTimeout function takes in a function name or an anonymous function as its first parameter and the number of milliseconds you'd like to delay before calling the function as the second parameter. For example, lets say you have a button that, when clicked, adds a new paragraph to a div called myDiv. You could handle it with jQuery like this:

  $('#button-id').click(addParagraph);
 
  function addParagraph() {
     $('#myDiv').append('<p>hello</p>');
  }

You should already be familiar with this kind of thing, because we've done it in class.

However, let's say that you didn't want to add the element to the page right away. Instead, you wanted to add the element after waiting for 2 seconds. You can use the setTimeout function to accomplish this.

  // When the button is clicked, create a new timer that will call the
  // addParagraph function after 2 seconds
  $('#button-id').click(function) {
     setTimeout(addParagraph, 2000);
  };
 
  function addParagraph() {
     $('#myDiv').append('<p>hello</p>');
  }

The setTimeout function above will delay the call to addParagraph for 2000 milliseconds, which is the same as 2 seconds. setTimeout will take in the name of a function as the first parameter:

  // Call functionName after 1 second
  setTimeout(functionName, 1000);

Or it will take in an anonymous function that you want to be called:

  // Call the function block after 1 second
  setTimeout(function() {
     // some code you want to be called
  }, 1000);

In both of these examples the functions will be called after 1000 milliseconds (remember, there are 1000 milliseconds in 1 second).

Using a Timer to Repeatedly Call a Function

The second type of timer uses the setInterval function. Like the setTimeout function, the setInterval function takes in a function name or an anonymous function block as its first parameter and a number in milliseconds as the second parameter:

  // Call myFunction every second
  setInterval(myFunction, 1000);

Or:

  // Call the function block every second
  setInterval(function() {
     // some code you want to  be called
  }, 1000);

What makes setInterval different is that it will repeatedly call the function, with a delay of milliseconds between each function call. In the examples above, the function will be called every 1000 milliseconds.

Stopping Timers

Both setTimeout and setInterval are functions that will wait a number of milliseconds before calling another function. What if you called setTimeout or setInterval, but then decided that you didn't want them to call the other function after all. How would you stop the function call from happening?

Stopping setTimeout

When you call the setTimeout function it returns a value you can store in a variable:

 var timer = setTimeout(functionName, 1000);

If you have stored setTimeout's return value you can use that value with another function called clearTimeout. The clearTimeout function will stop the timer from running if it hasn't already run yet.

For example, if I set a timer for 10,000 milliseconds (10 seconds), I can stop the timer before it runs and it will never call the function, even if 10 seconds goes by:

  // Create a new timer and store it in the timer variable
  var timer = setTimeout(myFunction, 10000);
  
  ... // whatever other code you might want to go here
  
  // If 10 seconds haven't passed already this will cancel the timer
  // and the function will never get called
  clearTimeout(timer);

In the example above, setTimeout creates a new timer, which gets stored in the timer variable. Later on in the code clearTimeout stops the timer from running. If 10 seconds already have gone by, clearTimeout won't do anything.

Stopping setInterval

Just like the setTimeout function, setInterval returns a timer that you can store in a variable:

  var timer = setInterval(functionName, 1000);

Once you have the timer that setInterval returned, you can use the clearInterval function to stop the timer from running. clearInterval takes in a timer variable and cancels the timer:

  // Create a new timer and store it in the timer variable
  var timer = setInterval(myFunction, 10000);
  
  ... // whatever other code you might want to go here
  
  // Stop the timer from running. This will prevent the
  // timer from calling the function again
  clearInterval(timer);

The clearInterval function will take the timer that his been running and stop it from running again. setInteval repeatedly calls a function until clearInterval stops it from running again.

Activity

From this class, we will be using a template to build 2 timers. One that increments a number in a box, and one that creates a simple clock that counts up to 60 seconds and then resets itself.

You can download the template for the activity here.


Assignment 5

Due Friday November 19th

Your assignment this week is to create an animation that uses a timer to draw elements on the canvas. You can choose to draw any animation you want as long as it fulfills the following criteria:

  • It must use a timer to draw elements on the canvas, or to interact with elements on the canvas using either setTimeout or setInterval
  • It must draw multiple elements to the canvas. These can be circles, rectangles or whatever other shape is supported by Raphael.
  • Draw as many elements as you want, but draw at least 3 elements.
  • The elements must respond to a mouse event. The mouse event can be a click, a mouseover, mouseout or whatever other events are supported by Raphael.
  • The elements must change in some way in response to the mouse event. Remember that you can use the attr or animate functions to change the attributes on any Raphael element.

The rest of the animation is up to you. Remember that you can change the x and y position of an element using 'x' and 'y' (or 'cx' and 'cy' for circles) with the attr or animation functions:

  var circle = canvas.circle(5, 5, 10);
  
  // animate the circle to position x = 20, and y = 30
  circle.animate({ cx: 20, cy: 30 }, 200);
 
  var rect = canvas.circle(100, 100, 10, 10);
  
  // animate the rect to position x = 50, and y = 20
  circle.animate({ x: 50, y: 20 }, 500);

A list of other attributes you can modify is here.

Also remember that you can attach mouse events to Raphael elements in the same way that you can attach events with jQuery:

  var circle = canvas.circle(5, 5, 10);
  
  // change the color of the element when the user clicks on it
  circle.click(function() {
     circle.animate({ fill: '#6DBE9F' });
  });

Remember that you can find documentation and examples at the Raphael site, and you can use the Raphaël page from last week to see how to draw Raphaël elements.

You can also see a list of jQuery's event handlers here under Event helpers. Many of jQuery's helpers have the same names as Raphael's event helpers.

I have posted a sample project that shows you the kind of thing I'm looking for here. You can use it as a starting point if you'd like.

If you have any questions about the assignment let me know.

Final Project

We've covered a lot of topics in the class. I'd like you to create final project that incorporates at least 4 of the topics listed below.

The project is up to you. If you have a project for another class or something at work that could be made better using JavaScript, you are welcome to use it. If you have a personal portfolio that you'd like to make more exciting with JavaScript, that works too. You can also create a simple art project or game.

I'd like you to email your project idea before next week's class. If you are having a hard time coming up with a project, let me know and I can help you figure out something else.

The import thing is: don't panic. I'm not expecting anyone to become a JavaScript genius in this class. Your project can be simple. Just make sure to include at least 4 of the topics listed below.

Your final project will be due Friday December 10th, and you will present your project in class on December 13th.

Topics