In this section I will explain more about interaction with the DOM (Known as Events), and some other important and useful objects in JavaScript. Events gives more interaction for the user in which makes things happen on the web page. In this section I will cover: Math, Timers, Date, and page events.
Along with the Array, Numbers, Strings, and Booleans Objects. JavaScript has some other built-in objects that are very useful. The Math object is used to to a number of mathematical operations: roots, rounding, random numbers, powers, trigonometry, and more! Unlike other objects we do not need to create and instance as there is an already defined objects called "Math", so we would do Math.method or Math.property . Here are some of the commonly used ones:
Methods:
Properties: Which are all mathematical constants (constants are often capitalized)
Math.floor( Math.random()*10 + 1 ); // => Random number from [1,10] Math.sin( Math.PI ); // => 0 Math.cos( Math.PI ); // => -1 Math.floor(2.99); // => 2 Math.ceil(2.01); // => 3 Math.sqrt( Math.pow(x2-x1, 2) + Math.pow(y1-y2, 2) ); // Distance between (x1,y1) and (x2,y2)
Another one is the Date objects, which is used to get the Date and Time based on your system's clock. Unlike the Math object we do need to create an instance of the Date Class:
var date = new Date(); // There are more ways to create a date but this is the most common.
Common Methods:
Here is an example of getting the current day of the week:
var weekdays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]; var date = new Date(); var day = date.getDay(); alert("Today is "+weekdays[day]);
We can execute JavaScript with the interactions of DOM elements on the page, such as: clicking, on focus, mouse over, key stroke, webpage as loaded, etc (known as event handlers). In this way we can make our webpage a bit more interesting then just a static webpage.
The onclick events happens when we click an element.
Events can be applied to objects in two ways, either within the HTML or within your JavaScript:
In HTML
<element onclick="myFunction()"> ... </element>
In JavaScript
document.getElementById("myElement").onclick = function(){ ... }
This same syntax goes for all DOM events. In fact all the buttons you have seen have the onclick event on them. Here is an example: Let's assume that we have a button with the id="myButton", we want to alert "Hello World" when it's clicked. Here is how you would do it:
document.getElementById("myButton").onclick = function(){ alert("Hello World") }
Or we could do it in the HTML ( although generally it a better idea to do it in JavaScript ):
<button onclick="alert('Hello World')"> Run </button>
Some other commonly used events are:
Here is an example of onmouseout and onmouseover
document.getElementById("block2").onmouseover = function(){ this.innerHTML = "Mouse Over"; } document.getElementById("block2").onmouseout = function(){ this.innerHTML = "Mouse Out"; }
In some languages timers can be quite complex or hard to use, although in JavaScript timers are quite simple and easy to use. The two timing events in JavaScript are:
setInterval() Keeps executing the the given function at a time interval based on the milliseconds given. Note that it will keep executing the function, over and over, until we tell it to stop.
var count = 0; var myTimer = setInterval(function(){ counter() },1000); function counter(){ count++; document.getElementById("counter").innerHTML = count; }
We can use the clearInterval( timer ) function to stop the timer from going on forever. In this case the Stop button does this:
clearInterval(myTimer);
Note: You will need to make your timer variables such as "myTimer" global variables.
The setTimeout() function will wait a specified number of milliseconds, then execute a function once. Here is an example of an alert that will wait 5 seconds before executing:
myTimer2 = setTimeout(function(){ alert("Hello World") }, 5000);
We can use clearTimerout( timer ) to stop the function from calling. This is what the stop button does in this case:
clearTimeout(myTimer2);
I'm sure you noticed that I disabled my Run buttons when you clicked them. It's very important not to create a setInterval() or setTimeout() on the same variable before the first one is finished or cleared. Because it will only be possible to stop the last call and not the runs before, which can lead to serious problems with infinite timers. Here is the modified code for the last event that disables the run button:
var myTimer2; function outFunction(){ // Called when Run button is clicked myTimer2 = setTimeout(function(){ alert("Hello World"); document.getElementById("run2").disabled = false; }, 5000); document.getElementById("run2").disabled = true; } function stopTime(){ // Called when Stop button is clicked clearTimeout(myTimer2); document.getElementById("run2").disabled = false; }
In that past we normally used cookies as storage on the clients machine, although cookies were small and not too secure. With HTML 5 becoming the standard there is a new way to store client-side information known as Web Storage or DOM Storage, there are two JavaScript objects that support HTML5 storage:
Currently we can store up to 5 Megabytes of information, much more than what cookies could store. HTML5 storage is also more secure that cookie storage.
Here is how to create a variable that uses localStorage:
localStorage.myVariable = ... ;
Here is how to create a variable that uses sessionStorage:
sessionStorage.myVariable = ... ;
And here is how you can check if a particular localStorage or sessionStorage variable exist or not:
if(localStorage.myVariable){ // It exist, change it. } else { // It doesn't exist, make it. }
Now for a simple example I will store button clicks in both session and local storage:
And here is the code below:
function localStore(){ if(localStorage.clicks){ localStorage.clicks++; } else { localStorage.clicks = 1; } document.getElementById("localStore").innerHTML = "Local Clicks : " + localStorage.clicks; } function sessionStore(){ if(sessionStorage.clicks){ sessionStorage.clicks++; } else { sessionStorage.clicks = 1; } document.getElementById("sessionStore").innerHTML = "Session Clicks : " + sessionStorage.clicks; } document.getElementById("localStore").onclick = function(){ localStore(); } document.getElementById("sessionStore").onclick = function(){ sessionStore(); }
Here are some important points we went over:
JS Objects : Built-in JS objects that we can use.
DOM Events : Even triggers that provides interaction with the web page.
Timers: Events used for timing with JavaScript.
Storage : Used to store information cliently.
Thank you for reading my introduction to Programing with JavaScript tutorial! If you have any (questions/comments/criticism) you can e-mail me at : spdwiecz@iupui.edu .