- Form validation and processing
- Interactive slideshows
- Games
- Single-page webapps
- ...anything that involves user interaction.
In IE 9+ (and all other browsers):
domNode.addEventListener(eventType, eventListener, useCapture);
<button id="counter">0</button> <script> var counterButton = document.getElementById('counter'); function onButtonClick() { counterButton.innerHTML = parseInt(counterButton.innerHTML) + 1; } counterButton.addEventListener('click', onButtonClick, false); </script>
Last lesson we learned about the Document Object Model, and how it allows us to manipulate elements on a web page. Most of the time we want to do that manipulation as a result of a user's interaction with the page. That's where 'events' come in. An 'event' is a type of object that is created when the user interacts with a web page. Events are related to the element the user interacted with, for example when a user clicks a link, a 'click' event is created for that link a element. To trigger some code to run when a particular event happens, we need to create an 'event listener'.
The browser triggers many events. A short list:
mousedown
, mouseup
, click
, dblclick
, mousemove
, mouseover
, mousewheel
, mouseout
, contextmenu
touchstart
, touchmove
, touchend
, touchcancel
keydown
, keypress
, keyup
focus
, blur
, change
, submit
scroll
, resize
, hashchange
, load
, unload
When your event listener is called, the browser passes an event object with information about the event into the function.
Each event type has different properties. For example, MouseEvent reports the clicked coordinates:
<img id="kitten" src="http://placekitten.com/200/300"> <div id="info"></div> <script> var kittenImg = document.getElementById('kitten'); var infoDiv = document.getElementById('info'); function onClick(event) { info.innerHTML = 'You clicked on ' + event.clientX + ' , ' + event.clientY; } kittenImg.addEventListener('click', onClick, false); </script>
A common use of events is to process form input, either by responding to button click events or input click/change events.
<input id="myname" type="text"> <button id="button">Say My Name</button> <script> var button = document.getElementById('button'); function onClick(event) { var myName = document.getElementById("myname").value; alert("Hi, " + myName); } button.addEventListener('click', onClick); </script>
When you run JS in the browser, it gives you the window
object with many useful properties and methods:
window.location.href; window.navigator.userAgent; window.scrollTo(10, 50); window.alert("Hello world!");
The window
object is the assumed global object on a page, so:
window.alert("Hi!");
...is the same as:
alert("Hi");
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:
function makeImageBigger() { var img = document.getElementsByTagName('img')[0]; img.setAttribute('width', img.width+10); } window.setInterval(makeImageBigger, 1000);
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); function fadeAway() { 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'; function watchKittyFall() { 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.
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; function fadeAway() { img.style.opacity = img.style.opacity - .1; if (img.style.opacity < .5) { window.clearInterval(fadeTimer); } } var fadeTimer = window.setInterval(fadeAway, 100);