Your code is dependent on the IE event model, which creates a global window.event object for each event. It is deprecated in favour of the W3C event model (supported by Firefox and others), but still supported in IE for backward compatibility.
You need to pass the event object to the function:
<button onclick="test(event)">Test</button>
then in the function:
function test(event){
alert(event);
}
If you attach the listener using addEventListner, the event object is passed to the listener as the first argument by default:
document.querySelector('#buttonID').addEventListener('click', test, false);
You can also add listeners directly as properties:
document.querySelector('#buttonID').onclick = test;
which passes the event object as the first parameter in the W3C event model, but not in IE so the function must test and use window.event if event is undefined:
function test(event){
event = event || window.event;
console.log(event);
}
A very simple function to add a listener that works in all browser is:
function addEvent(element, event, fn) {
if (element.addEventListener) {
element.addEventListener(event, fn, false);
} else if (element.attachEvent) {
element.attachEvent('on' + event, fn);
}
}
Note that in IE, this will not be set to the element that called the event. If you need to fix that, then the following will do that:
function addEvent(element, evt, fn) {
if (element.addEventListener) {
element.addEventListener(evt, fn, false);
} else if (element.attachEvent) {
element.attachEvent('on' + evt, function() {
fn.call(element, event);
});
}
}
And use it like:
addEvent(document.getElementById('buttonID', 'click', test);
There are more sophisticated versions, but the above should suffice. It creates unnecessary circular references though, you might want to avoid those. To do that, you need something like:
function addEvent(element, evt, fn) {
if (element.addEventListener) {
element.addEventListener(evt, fn, false);
} else if (element.attachEvent) {
element.attachEvent('on' + evt, (function(fn, element) {
return function() {
fn.call(element, event);
};
}(fn, element)));
}
// Remove obvious circular reference
element = null;
}
The bottom line is that in the vast majority of cases, adding listeners as properties is simple, cross browser and sufficient. It only falls down if you need to add more than one listener to an element for the same event, but even that is fairly easily accommodated.