JavaScript Events & Objects

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:

  • Math.random() - Returns a random number between 0.0 and 1.0 : range [0,1)
  • Math.round(number) - Returns the number given to the nearest integer.
    • Math.floor(number) - Returns an integer rounded down (3.8 -> 3)
    • Math.ceil(number) - Returns an integer rounded up (3.2 -> 4)
  • Math.sin(num) , Math.cos(num), Math.tan(num) , ... - Applys trigonometric functions to the number.
  • Math.max(num1,num2,...) , Math.min(num1,num2,...) - Returns the max/min of a list( but not an array) of numbers.
    • Math.max.apply(0,array) - This will work for an array
  • Math.abs(number) - Returns the absolute value of the number.
  • Math.log(number) - Returns the natural logarithm of a number.
  • Math.sqrt(number) - Returns the square root of a number.
  • Math.pow(num, exp) - Returns the number taken the the power of the exp.

Properties: Which are all mathematical constants (constants are often capitalized)

  • Math.PI - Returns π (~3.14159)
  • Math.E - Returns e (~2.718)
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:

  • date.getDate() - Returns the day of the month (1 to 31)
  • date.getDay() - Returns the day of the week ( 0[Sun] to 6[Sat] )
  • date.getMonth() - Returns the current month (0 to 11)
  • date.getYear() - Returns the current year ( YYYY , ex: 2014)
  • date.getHours() - Returns the current hour (0 to 23)
  • date.getMinutes() - Returns the current minute (0 to 59)
  • date.getSeconds() - Returns the current second (0 to 59)
  • date.getMilliseconds() - Returns the current millisecond (0 to 999)
  • date.toLocaleDateString() - Returns a formatted date as a string (ex: "1/10/2014")
  • date.toLocaleTimeString() - Returns a formatted date as a string (ex: "10:45 AM")

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.

Click

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:

  • onload - Triggers when the entire webpage loads.
  • onmouseover - Triggers when the mouse is over an element.
  • onmouseout - Triggers when the mouse leaves an element.
  • onmousedown - Triggers when the mouse is pressed on an element.
  • onmouseup - Triggers when the mouse is released from an element.
  • onmousemove - Triggers when the mouse is moved inside an element.
  • onfocus - Trigers when an element is focused on (like clicking an input box).

Here is an example of onmouseout and onmouseover

Hello

document.getElementById("block2").onmouseover = function(){
   this.innerHTML = "Mouse Over";
}

document.getElementById("block2").onmouseout = function(){
   this.innerHTML = "Mouse Out";
}
Remember window.onload = function() { ... } ? Yes it is a DOM event.

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(function, milliseconds)
  • setTimeout(function, milliseconds)

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.

0

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;  
}
Both the timer events are DOM window events, they are actually called as: window.setTimeout(...). But they don't need to be written with the window prefix.

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:

  • localStorage - Stores the information cliently on a database, information is not lost when the browser is closed.
  • sessionStorage - Store the information temporarily in a page session, but the information is lost when the page is closed.

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.

  • Math - Used to perform common mathematical operations. (Math.sin(n) , Math.round(n), Math.PI, ...)
  • Date - Uses the System Clock to find the current Date along with (seconds,minutes, ... ,Day,Month,...)

DOM Events : Even triggers that provides interaction with the web page.

  • onclick : Triggered when you click the mouse button on an element.
  • onmouseover : Triggered when the mouse is over an element.
  • onmouseout : Triggered when the mouse leaves an element.

Timers: Events used for timing with JavaScript.

  • setInterval(function, milliseconds) - Keeps executing the the given function at a time interval.
  • setTimeout(function, milliseconds) - Wait the given number of milliseconds then execute the function.

Storage : Used to store information cliently.

  • localStorage - Stores the information permanently in a client-side database.
  • sessionStorage - Stores information for the current browsers session, but is lost when it's session ends.

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 .

Spencer Wieczorek