[JavaScript] Event Object

When an event is triggered, the event object is passed into the handler as an argument.

1. Event Object

The standard DOM Event object provides 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 additional 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

Also event objects provide the following methods:

  • preventDefault() : to cancel any default action
  • stopPropagation() : to prevent further propagation of an event
document.getElementById("btn1").onclick = function (e) {
  alert(e.type);
};

 

2. “window.event” Object

Traditionally, IE uses the global “window.event” object. IE9 and later support the stanard event handling features. But if you still need to support IE8 and older, chances are high that you have to deal with the “window.event” object.

Note that the “window.event” object is deprecated and only for the legacy code. Do not use this object in the new code even though IE is the only browser you concern.

 

3. jQuery Event Object

jQuery normalizes the properties and methods for cross-browser consistency.

  • target
  • pageX
  • pageY
  • which
  • preventDefault() / isDefaultPrevented() 
  • stopPropagation() / isPropagationStopped()
$(document).ready(function () {
  $("#btn1").click(function (e) {
    alert(e.target.id + ", " + e.type);
  });
});

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