/**
* 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);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.