Week 02, Day 04.

What we covered today:

Events

Adding Event Listeners

In IE 9+ (and all other browsers):

domNode.addEventListener(eventType, eventListener, useCapture);

// HTML = <button id="counter">0</button>

var counterButton = document.getElementById('counter');
var button = document.querySelector('button')
button.addEventListener('click', makeMadLib);

var onButtonClick = function() {
    counterButton.innerHTML = parseInt(counterButton.innerHTML) + 1;
};
counterButton.addEventListener('click', onButtonClick, false);

Some Event Types

The browser triggers many events. A short list:

  • mouse events (MouseEvent): mousedown, mouseup , click, dblclick, mousemove, mouseover, mousewheel , mouseout, contextmenu
  • touch events (TouchEvent): touchstart, touchmove, touchend, touchcancel
  • keyboard events (KeyboardEvent): keydown, keypress, keyup
  • form events: focus, blur, change, submit
  • window events: scroll, resize, hashchange, load, unload

Getting Details from a Form

// HTML
// <input id="myname" type="text">
// <button id="button">Say My Name</button>

var button = document.getElementById('button');
var onClick = function(event) {
    var myName = document.getElementById("myname").value;
    alert("Hi, " + myName);
};
button.addEventListener('click', onClick);

Get into this exercise!

Window

When you run JS in the browser, it gives you the window object with many useful properties and methods:

window.location.href; // Will return the URL
window.navigator.userAgent; // Tell you about the browser
window.scrollTo(10, 50);

Lots of things that we have been using are actually a part of the window object. As the window object is the assumed global object on a page.

window.alert("Hello world!"); // Same things
alert("Hello World!");

window.console.log("Hi"); // Same things
console.log("Hi");

Animation in JS

The standard way to animate in JS is to use these 2 window methods.

To call a function once after a delay:

window.setTimeout(callbackFunction, delayMilliseconds);

To call a function repeatedly, with specified interval between each call:

window.setInterval(callbackFunction, delayMilliseconds);

Commonly used to animate DOM node attributes:

var makeImageBigger = function() {
  var img = document.getElementsByTagName('img')[0];
  img.setAttribute('width', img.width+10);
};
window.setInterval(makeImageBigger, 1000);

Animating Styles

It's also common to animate CSS styles for size, transparency, position, and color:

var img = document.getElementsByTagName('img')[0];
img.style.opacity = 1.0;
window.setInterval(fadeAway, 1000);
var fadeAway = function() {
  img.style.opacity = img.style.opacity - .1;
};

// Note: opacity is 1E9+ only (plus all other browsers).
//
var img = document.getElementsByTagName('img')[0];
img.style.position = 'absolute';
img.style.top = '0px';
var watchKittyFall = function() {
  var oldTop = parseInt(img.style.top);
  var newTop = oldTop + 10;
  img.style.top = newTop + 'px';
};

window.setInterval(watchKittyFall, 1000);
// Note: you must specify (and strip) units.

Stopping an Animation

To stop at an animation at a certain point, store the timer into a variable and clear with one of these methods:

window.clearTimeout(timer);
window.clearInterval(timer);
var img = document.getElementsByTagName('img')[0];
img.style.opacity = 1.0;

var fadeAway = function() {
  img.style.opacity = img.style.opacity - .1;
  if (img.style.opacity < .5) {
    window.clearInterval(fadeTimer);
  }
};
var fadeTimer = window.setInterval(fadeAway, 100);

Have a crack at these exercises

Homework

Here it is.

The Cat Walk

Who needs Milan when you have JavaScript?

Start with this webpage, which has a single img tag of an animated GIF of a cat walking.

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <title>Cat Walk</title>
 </head>
 <body>

  <img style="position:absolute;" src="http://www.anniemation.com/clip_art/images/cat-walk.gif">

 </body>
</html>
  • Create a new Javascript file and link to it with a script tag at the bottom.
  • Create a variable to store a reference to the img.
  • Change the style of the img to have a "left" of "0px", so that it starts at the left hand of the screens.
  • Create a function called catWalk() that moves the cat 10 pixels to the right of where it started, by changing the "left" style property.
  • Call that function every 50 milliseconds. Your cat should now be moving across the screen from left to right. Hurrah!

  • Bonus #1: When the cat reaches the right-hand of the screen, restart them at the left hand side ("0px"). So they should keep walking from left to right across the screen, forever and ever.

  • Bonus #2: When the cat reaches the right-hand of the screen, make them move backwards instead. They should keep walking back and forth forever and ever.

  • Bonus #3: When the cat reaches the middle of the screen, replace the img with an image of a cat dancing, keep it dancing for 10 seconds, and then replace the img with the original image and have it continue the walk.