Events JS Home  <<  JS Advanced  <<  Events

In this lesson we look at events and how we can bring our pages to life using JavaScript to react to them.

So what is an event? Events are part of the DOM Event Model provided by all web browsers and are executed when a change happens on a web page. An event can be a page loading, the user clicking a mouse, the window being resized to name a few. The event represents the exact moment when the action happened, for instance the web browser will signal a click event when you click a mouse button.

Where does JavaScript come in? JavaScript is an event-driven language and so when an event happens we can utilize JavaScript, normally in the form of a function to react to the event. This is where the real power of JavaScript comes to the fore and allows us to interact with events as they happen and act accordingly.

The JavaScript Event Model

Before we look at the various JavaScript events available its worth mentioning The JavaScript Event Model and how it works. JavaScript is not a multi-threaded language like Java or C++ but a single-threaded language. This means we don't have to worry about multiple events hitting a piece of code at the same time and possibly updating and corrupting shared data. Lets look at a simple piece of code to show the single-threaded model.

The output shown for the code below may surprise you. You may have been expecting the output value of idx to be 1 and 2 or maybe 2 and 1, but we get the value of 3 and 3. This is because the setTimeout event is placed in a queue of events which get executed one at a time (single-thread model). Therefore the setTimeout events don't get run until the code has ended and it hits the top of the queue. By this time the value of idx is 3 which is output below. Don't worry for now about the code used to display the result as this is covered in the jQuery section of the site.


$(function(){
  for (var idx = 1; idx < 3; idx++) {
    setTimeout(function(){ 
      $('#div1').append('<br> The variable "idx" = ' + idx);
    },  0);
  };
});


div1. The results of running the above code.

Event Attributes

Let's take a look at the events available in browsers and how they are triggered.

Event Attributes And Their Triggers
Attribute Event Triggered By
Form Events
onblur An element loses focus when the mouse is moved away or by tabbing
onchange A control loses input focus and its value has been modified since focus was gained
onfocus An element gains focus when the mouse is moved onto it or by tabbing
onreset A form has been reset
onselect A user selects some text from a text field, input or textarea
onsubmit A form has been submitted
Keyboard Events
onkeydown A key on the keyboard is pressed
onkeypress A key on the keyboard is pressed
This is really a sequence of events onkeydown, onkeypress
onkeyup A key on the keyboard is released
Mouse Events
onclick The user has clicked the mouse over an element
This is really a sequence of events onmousedown, onmouseup, click
ondblclick The user has double clicked the mouse over an element
onmousedown The user has pressed a mouse button while over an element
onmousemove The user has moved the mouse while over an element
onmouseout The user has moved the mouse off of an element
onmouseover The user has moved the mouse onto an element
onmouseup The user has released a mouse button while over an element
Window/Frame/Object Events
onabort An object or image has been stopped from loading before complete
onerror An object or image has failed to load completely
onload User agent has finished loading all content within a document, including window, frames, objects and images
onresize The window or frame has been resized
onscroll The window or frame has been scrolled
onunload User agent has finished unloading all content from a window or frame

Working with events

There are three ways to deal with events when using JavaScript which we will cover in this section.

Inline Event Registration

Inline event registration allows you to assign an event handler to a HTML element on your page. This technique appears very easy to use at first but comes with side-effects, they may not become apparent until you have to modify a page. Because we are handling the event inline we are mixing HTML (structure) with Javascript (behaviour) which is not best practice. Another issue is maintainability. If you have inline events dotted all over your HTML pages and you have to modify them all, this is a time consuming and error-prone process.

Lets see an example of inline event registration in action.

The function changeValue(obj) should change the text of the button below.


// Change button value.
function changeValue(obj) {
  obj.value = 'button text changed using Inline Event';
}

// The HTML for the  'Inline Event' button is:
<p><input type="button" value="Inline Event"
       onclick="changeValue(this)" /></p> 
			

Press the button below to action the above code:

DOM Element Event Registration

With DOM element event registration we get access to the element required and put the required process into a function that is executed when the button is clicked. We can put this function into an external javascript file or into the html header. With this method of event registration there is no mixing of HTML (structure) with Javascript (behaviour). The downside of the DOM element event registration approach is that only one handler can be set for each element and for each event.

Lets see an example of DOM element event registration in action.

The anonymous function should put up an alert box.


// Change button value.
document.getElementById('helloButton').onclick = function() {
  alert('Hello world');
};

// The HTML for the  'Dom Element' button is:
<p><button name="helloButton">Click Me></p> 
			

Press the button below to action the above code:

Listener Event Registration

With listener event registration we get access to the element required and put the required process into an event listener that is actioned when the appropriate handle is triggered. We can put this function into an external javascript file or into the html header. With this method of event registration there is no mixing of HTML (structure) with Javascript (behaviour). Using listener event registration we can have multilple handles covering multiple events for the same element.

Always use this method of event registration

Lets see an example of listener event registration in action.

The event listener should put up an alert box. Sadly Microsoft went off in a different direction with event handling and use attachEvent instead of addEventListener in versions of IE before 9. So it is something all web developers have to live with, for now at least. When we get onto the JQuery lessons this issue is negated as JQuery handles events in a way that the browser used doesn't matter.


// Change button value.
var holdDOMElement = document.getElementById('helloUniButton')
if (holdDOMElement.addEventListener) {  // all browsers except IE6 IE7 IE8
  holdDOMElement.addEventListener('click', function() {
    alert('Hello Universe');
  }, false);
}
else {
  if (holdDOMElement.attachEvent) {   // IE before version 9
    holdDOMElement.attachEvent('click', function() {
      alert('Hello Universe');
    }, false);
  }
}

// The HTML for the  'Listener Event' button is:
<p><button name="helloUniButton">Click Here></p> 
			

Press the button below to action the above code:

Lesson 7 Complete

In this lesson we looked at events and how we can use JavaScript to react to them.