Attaching an Event

There are a lot of ways to attach an event to a DOM element. Some are like using inline JavaScript in your HTML or by using other below methods.

  • Event handlers
  • Event listeners
Event Handlers

Using Event handlers we can attach an event to a DOM element.

Below is an example to attach an event click to a button element through an Event Handler.

Syntax

You get the point; every event is on<event> when using event handlers.

/* wrap it in an anonymous function to contain the variables */
(function() {
    // HTML: <button type="button" id="btn">a button</button>
    // save the button to a variable
    var btn = document.getElementById('btn');
    
    // Use an event handler to attach the "onclick" event
    btn.onclick = function() {
        // alert inside this anonymous callback function
        alert('clicked the button');
    }
})();

In the above example a button element with an id value of "btn" and is attached a click event to it in the form of "onclick" to an anonymous function. When a button is clicked it alerts the text "clicked the button."

The events are prefaced with the word "on." It applies to all events: onsubmit, onchange, onfocus, onblur, onmouseover, onmouseout, ontouchstart, ongesturestart and so on.

Note
You can attach only a single function to a specific event of a DOM node. You can’t attach two click functions to the same button. To overcome this limitation you can use an event listener instead of an event handler.
Event Listeners

Event listeners are similar to Event handlers. Similar to event handlers you need a DOM element to attach them to identify the event, and need a function to call.

The difference is that you can assign multiple functions to the same DOM element and event.

Below is an syntax of an event listener using an anonymous function.

// event listener with an anonymous function
element.addeventListenter("event", function(){
// stuff you want the function to do
}, false);

The above event listener is made up of four parts.

  • The DOM element ("element")
  • The event type ("event")
  • The eventListener , aka the function (anonymous function)
  • An optional Boolean value used to initiate something called "capture" (value set to false)

Setting optional Boolean value to true is like telling to all the parent DOM nodes that an event is firing on a particular node. Setting to false prevents this behavior because. It is unnecessary. It's called "event propagation."

Example for adding a Basic Click Event Through a Listener on a button, which has an ID value of "btn."

/* wrap it in an anonymous function to contain the variables */
(function() {
    /* HTML: <button type="button" id="btn">a button</button> */
    // save the button to a variable
    var btn = document.getElementById("btn");
    // attach a "click" listener to the button
    btn.addEventListener("click", function() {
        // alert inside this anonymous callback function
        alert(''
            clicked the button '');
    }, false);
})();
Note
Each browser event handler is registered in a context. When you call addEventListener, you are calling it as a method on the whole window because in the browser the global scope is equivalent to the window object. Every DOM element has its own addEventListener method, which allows you to listen specifically on that element.
Binding Events

The function inside an addEventListener() method is called an event listener. The functions inside the addEventListener() method don't have parentheses.

Binding an Event to a DOM Element

// save the DOM element you want to attach an event to
var btn = document.getElementByID("btn");

// define your function normally
function alertMessage() {
    alert("clicked the button");
}
// or use a predefined function (event handler), "alertMessage"
btn.addEventListener("click", alertMessage, false);

To pass arguments into a function while using addEventListener(), you need to use the function as a callback instead by nesting it inside an anonymous function. 

The below example shows you how to use an anonymous function and a callback function.

// save the DOM element you want to attach an event to
var btn = document.getElementByID("btn");
// define your function normally
function alertMessage(message) {
    alert(message);
}
// or use a predefined function (event handler), "alertMessage"
btn.addEventListener("click", function() {
    // callback function!
    alertMessage("clicked the button");
}, false);

It is very similar to the previous example but instead of simply calling a function, you can pass parameters into it.

Another example: If you have a list of buttons, you can register a single click handler on the button using the target property to figure out whether a button was clicked, rather than register individual handlers on all of the buttons.

<button>A</button>
<button>B</button>
<button>C</button>

<script>
document.body.addEventListener('click', function(event) {
    if (event.target.nodeName == 'BUTTON')
        console.log('Clicked', event.target.textContent);
});
</script>
Unbinding Events

After you bind (attach) events to DOM elements if you want to unbind (detach) events from DOM nodes you can remove the listener using the method removeEventListener.

Removing an Event Listener
    if (btn.removeEventListener) {
        // if removeEventListener is supported
        btn.removeEventListener( 'click', alertMessage, false);
    } else {
        // if removeEventListener isn't supported (IE8 and below)
        btn.detachEvent( 'click', alertMessage); 
    }< /pre>
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +