JavaScript - Register event handlers and Detect events

Events are actions that an user performs on a page.
For example, clicking or positioning the mouse over an element, writing in a text input field, or scrolling the page, are events carried out by the user.
To allow you to run some JS code when these events occur, JavaScript provides us with event handlers, like: onclick, onmouseover, onkeypress, onscroll, etc.

Registering event handlers

The old way to execute some instructions, a function when an event is triggered, is by placing the event handler name within the HTML tag in which the event must be detected.
For example, when the user clicks on this link, the event handler is triggered and the function someFunction() is executed:
<a href="#" onclick="someFunction();" title="Text">Link</a>

• You can also register event handlers without addind the event handler within the HTML tag.
The best way to register an event handling function cross–browser is with this syntax:
element.event_handler = someFunction;
- element represents the element that trigger the event_handler, which will execute the function someFunction.
- Note that in the registration of an event handler you do not use parentheses () at the name of the function that is called.

Example, when click on a DIV, it displays an Alert window:
<div id="dvid" style="width:100px; background:#a8eda9; cursor:pointer;">Click here</div>
<script type="text/javascript"><!--
var elm = document.getElementById('dvid');         // gets the element

// function to execute when the event is triggered
function aFunction() {
  alert('Click event detected');
}

// register an onclick event handler
elm.onclick = aFunction;
--></script>
Demo:
Click here

Event handler and Anonymous function

The function that will be executed when the event is triggered can also be created in the expresion which register the event handler.
Syntax:
element.event_handler = function() { // code to execute };
Example:
<div id="dvid" style="width:100px; background:#a8eda9; cursor:pointer;">Click here</div>
<script type="text/javascript"><!--
var elm = document.getElementById('dvid');         // gets the element

// register an onclick event handler
elm.onclick = function() {
  alert('Click event - anoymous function');
};
--></script>
Demo:
Click here

• To remove the event handler, assign it the null value:
element.event_handler = null;
- Example. When the user places the cursor over the tag with id="dvid", alerts a message, then removes the "onmouseover" event registration, so, when the users places again the mouse over that item, nothing happens.
<div id="dvid" style="width:100px; background:#a8eda9;">Place the cursor here</div>
<script type="text/javascript"><!--
var elm = document.getElementById('dvid');         // gets the element

// register an onmouseover event handler
elm.onmouseover = function() {
  alert('Place the mouse again over that text');
  elm.onmouseover = null;            // remove the registration
};
--></script>
Demo:
Place the cursor here

The this keyword

In JavaScript the this keyword always refers to the "owner" of a function. In the case of event handlers, this refers to the HTML element that trigger the event.

- Example. When the user clicks on the tag with id="dvid", JavaScript gets its content, displays it into an Alert window and changes its background color.
<div id="dvid" style="width:125px; background:#a8eda9; cursor:pointer;">Example with this</div>
<script type="text/javascript"><!--
var elm = document.getElementById('dvid');         // gets the element

// register an onclick event handler
elm.onclick = function() {
  // gets the HTML content of the current element (that triggers the event)
  var elm_cnt = this.innerHTML;

  alert(elm_cnt);        // alert that content

  // sets a blue background color to the curent element
  this.style.background = 'blue';
};
--></script>
Demo (click on the text below):
Example with this

Register and Detect events with addEventListener()

There is also another way to register events, with the addEventListener() method.
Syntax:
element.addEventListener('event', someFunction, use_capture);
- event - is a string representing the event type to listen for, without the prefix "on" ("click", "mouseover", "mouseout", ...).
- someFunction - a function that is called when "event" is dispatched.
- use_capture - (optional) a boolean value (true or false). It is meant to state whether the event handler should be executed in the capturing or in the bubbling phase. If you're not certain whether you want capturing or bubbling, use false (bubbling).
This method is not supported by all major browsers, so it's beter to use the traditional model, presented above.

- Example. When the user places the mouse over a LI element, that HTML element gets a green background, and removes the background when mouseout.
<ul>
 <li>WebDevelopment - coursesweb.net</li>
 <li>Free Courses - www.marplo.net</li>
 <li>PHP Manual - www.php.net</li>
</ul>
<script type="text/javascript"><!--
var elm_li = document.getElementsByTagName('li');         // gets all the <li> tags

// function to execute when the mouseover is triggered
function over() {
  // sets a background color to the curent element
  this.style.background = '#07da08';
}

// function to execute when the mouseout is triggered
function out() {
  // remove the background color of the curent element
  this.style.background = 'none';
}

// traverse the object with the LI elements
for(var i=0; i<elm_li.length; i++) {
  // register mouseover and mouseout to each LI
  elm_li[i].addEventListener('mouseover', over, true);
  elm_li[i].addEventListener('mouseout', out, false);
}
--></script>
Demo (move the cursor over the list below):
  • WebDevelopment - coursesweb.net
  • Free Courses - www.marplo.net
  • PHP Manual - www.php.net

• To remove an event handler registered with addEventListener(), use the removeEventListener() method:
element.removeEventListener('event', someFunction, false);