[JavaScript] Events

Events and handlers are the basic programming model of JavaScript in web browsers. In most cases, you are going  to use JavaScript frameworks such as jQuery to minimize the browser inconsistencies and separate the code from the markup. But this post focuses on the native support of events and handlers.

1. Adding Handlers to Events

There are 3 ways to add handlers to events.

  • as an attribute to HTML tags
  • using the DOM object in the code
  • using the DOM methods – addEventListener() / removeEventListener()


To add the click event handler to the second button in code, you need to get the DOM element first.

function btnClicked() {
  alert("Button is clicked");
}

$(document).ready(function () {
  document.getElementById('click2').onclick = btnClicked;
});

Another way to add handlers to events is using the DOM methods.

  • addEventListener(type, listener) 
  • removeEventListener(type, listener)

The good side of the “addEventListener()” method is that you can add as many handlers as you want. The bad side is that it is not supported by IE8 or eariler.

function btnClicked1() {
  alert("1. Button is clicked");
}
function btnClicked2()
{
  alert("2. Button is clicked ");
}

$(document).ready(function () {
  var btn = document.getElementById('click2');
  btn.addEventListener("click", btnClicked1);
  btn.addEventListener("click", btnClicked2);
});

In Internet Explorer prior to IE 9, you have to use “attachEvent()” method.

[Note] In production environment, use the framework library such as jQuery. Do not handle browser support issues by yourself.

 

2. Event Object

You can pass the Event object as the first parameter of an event handler. When event is triggered, the appropriate event object is created and passed as an argument. It is very useful for keyboard or mouse events.

All event has the following properties :

  • bubbles : boolean
  • cancelable : boolean
  • target : the element that triggered event
  • type : the name of the event

Mouse and  Keyboard events has the following properties :

  • clientX : the horizontal coordinate of the mouse pointer
  • clientY : the vertical coordinate of the mouse pointer
  • button : which mouse button is clicked
  • altKey : flag for ALT key
  • ctrlKey : flag for CTRL key
  • shiftKey : flag for SHIFT key

Note that there is no direct way to get which key is pressed. I will explain later how to do it.

 

3. Mouse Events

Most commonly used mouse events are :

  • onclick : clicks on an element
  • ondblclick : double-clicks on an element
  • onmouseover : the pointer is moved onto an element
  • onmouseout : the pointer is out of an element
  • onmousedown : presses a mouse button over an element
  • onmouseup : releases a mouse button over an element
function btnClicked(e) {
  alert(e.type + " : " + e.clientX + ", " + e.clientY);
  alert("target : " + e.target.tagName + " - " + e.target.id);
}

$(document).ready(function () {
  document.getElementById('btn1').onclick = btnClicked;
});

 

4. Keyboard Events

Keyboard related are :

  • onkeydown : the user is pressing a key
  • onkeypress : the user presses a key
  • onkeyup : when the user releases a key

To get the which key is pressed, you need to do some work.

In general, you can use the “which” property of the event. But this property is not supported in IE 7 and 8. In older versions of IE, you need to use the “window.event.keyCode” property.

function keyPressed(e) {
  var keycode = null;
  if (window.event) {
    keycode = window.event.keyCode; // IE
  } else if (e) {
    keycode = e.which; // others
  }
  alert(keycode);
}

$(document).ready(function () {
  document.getElementById('text1').onkeypress = keyPressed;
});

 

5. Page / Window Events

  • onload : a page or <object> has been loaded
  • onresize : a page view is resized
  • onscroll : a page view is scrolled
  • onunload : a page has unloaded
function pageResized() {
  var w = 0;
  var h = 0;
  if (window.innerWidth) {
    // W3C and IE9
    w = window.innerWidth;
    h = window.innerHeight;
  } else {
    // legacy IE
    if (!(document.documentElement.clientWidth == 0)) {
      //strict mode
      w = document.documentElement.clientWidth;
      h = document.documentElement.clientHeight;
    } else {
      //quirks mode
      w = document.body.clientWidth;
      h = document.body.clientHeight;
    }
  }
  alert(w + ", " + h);
}

$(document).ready(function () {
  window.onresize = pageResized;
});

 

6. Form Events

  • onfocus : an element gets focus
  • onblur : an element loses focus
  • onchange : the content of an element, the selection, or the checked state have changed
  • onreset : when a form is reset
  • onselect : a user selects some  text for <input> and <textarea>
var txtBox = document.getElementById("text1");
txtBox.onfocus = function (e) {
  alert(e.target.id + " gets focus");
};
txtBox.onblur = function (e) {
  alert(e.target.id + " loses focus");
};
txtBox.onchange = function (e) {
  alert(e.target.value);
};

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s