Understanding event handlers in JavaScript

Understanding event handlers in JavaScript

What is event handlers? Its very powerful and useful;

They are JavaScript code that are not added inside the <script> tags, but rather, inside the html tags, that execute JavaScript when something is triggered or called, such as pressing a button, moving your mouse over a link, submitting a form and so on.

The basic syntax of these event handlers is:

name_of_handler=”JavaScript code here”

For example:

<a href="http://www.prasadk.com" onClick="alert('Hi')">prasadk.com Home</a>

Click here to have a look prasadk.com Home

This is certainly unlike a regular JavaScript code, here we are inserting it directly inside a HTML tag, via the onClick event handler. When the above link is clicked, the user will first see an alert message before being taken to home / index page of http://www.prasadk.com.

Different event handlers with with different HTML tags. For example, while “onclick” can be inserted into most HTML tags to respond to that tag’s onclick action, something like “onload” only works inside the <body> and <img> tags.

Listed some of the most commonly used event handlers supported by JavaScript below:

 Event Handlers:

onclick: Use this to invoke JavaScript on clicking (a link, or form boxes)
onload: Use this to invoke JavaScript after the page or an image has finished loading.
onmouseover: Use this to invoke JavaScript if the mouse has been hovered on some link
onmouseout: Use this to invoke JavaScript if the mouse goes pass some link or gets triggered when mouse is taken out of link
onunload: Use this to invoke JavaScript right after someone leaves the page.

In OOP / Object Oriented Event Handlers in Javascript

By default, when an event occurs in javascript, the this reference in the handler function refers to the HTML element.
But what if we want the ‘this’ to refer to the class that houses our handler? We can use the bind()function – see below.

It works like this / snippet


Function.prototype.bind = function (obj) {
    var fn = this;
    return function () {
      var args = [this];

      for (var i = 0, ix = arguments.length; i < ix; i++) {
        args.push(arguments[i]);
      }
      return fn.apply(obj, args);
    }
  }

  function myClass() {
    this.name = "Member variable of myClass()!!";

    myClass.prototype.alertThis = function(el, e) {
      if (!e) var e = window.event;
      alert(this.name);   //we have access to our class object
      alert("id: " + el.id);       //we have access to the element that was clicked
      alert("id: " + e.target.id); //we have access to our event
    }.bind(this);

    var el = document.getElementById("myDiv");
    el.onclick=this.alertThis;
  }

  function onLoad() {
    window.c = new myClass();
  }

  if (window.addEventListener){
    window.addEventListener('load', onLoad, false); 
  } else if (window.attachEvent){
    window.attachEvent('onload', onLoad);
  }

 

Touch Event handlers for touch screen devices :

Some more event handlers are like touchstart, touchmove, touchend, touchcancel, tap, taphold, swipe, swipeleft, swiperight

snippet given below

function touchHandler(event) {
    var touch = event.changedTouches[0];

    var simulatedEvent = document.createEvent("MouseEvent");
        simulatedEvent.initMouseEvent({
        touchstart: "mousedown",
        touchmove: "mousemove",
        touchend: "mouseup"
    }[event.type], true, true, window, 1,
        touch.screenX, touch.screenY,
        touch.clientX, touch.clientY, false,
        false, false, false, 0, null);

    touch.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}

function init() {
    document.addEventListener("touchstart", touchHandler, true);
    document.addEventListener("touchmove", touchHandler, true);
    document.addEventListener("touchend", touchHandler, true);
    document.addEventListener("touchcancel", touchHandler, true);
}
$(document).ready(function(){
  init();
});

 

PN : while handling the touch event don’t forget to include jQuery, jQuery UI and jQuery mobile from cdn