Event Handling Basics

by phate101101

HTML

<div id="container">
 <!-- the old, inline way --><a href="#" onclick="console.log('Hi', this); return false;">A link</a>
 <a href="#" id="link2">Second Link</a>
 <a href="#" id="link3">Third Link</a>

</div>

CSS

a {
    display:block
}

JavaScript

/**
 * traditional, DOM handlers
 */
var link2 = document.getElementById("link2");

link2.onclick = function (e) {
    console.log(e); // the event
    console.log(this); // refers to element
    return false;
}

// remove it with:
//link2.onclick = null;

// or...
window.onload = function (e) {
    // do something once the page is fully loaded into the dom
    console.log("Loaded", e);
}

/**
 * Event Listener way
 */
var link3 = document.querySelector("#link3");

var moListener = function (e) {
    console.log("Hover over link 3");
    this.style.backgroundColor = "#eeeeee";
}

link3.addEventListener('mouseover',
    moListener,
    false // use capture method
);
// remove with
//link3.removeEventListener('mouseover', moListener);

// supports anonymous functions
link3.addEventListener('click',
    function (e) {
        console.log("Third link clicked", e);
    },
    false // use capture method
);

// "this" refers to the current element (when using the w3c method)
link3.addEventListener('mouseout',
    function (e) {
        console.log("Third link mouse out", e);
        this.style.backgroundColor = "#ffffff";
    },
    false // use capture method
);

// ie8 and below... 
// "this" keyword refers to the window... 
// event object is not set, its global on window object
/*
var handlerFunction = function(e) {
    e = e || window.event;
    // "this" is not available, use event properties
}
link3.attachEvent('click', handlerFunction);
*/
//link3.detachEvent('click', functionNameVar);