It depends on the browsers you have to support, but if you are lucky and only worry about modern browsers, you can use .addEventListener()
var thing = document.getElementById('thing');
thing.addEventListener('click', function(e) {
}, false);
If you're out of luck, you'll have to come up with a cross browser solution.
var thing = document.getElementById('thing');
addEvent(thing, 'click', function() {
});
function addEvent(elem, event, callback) {
if (elem.addEventListener) {
elem.addEventListener(event, callback, false);
} else if (elem.attachEvent) {
elem.attachEvent('on' + event, function() {
callback.apply(elem, arguments);
});
} else {
elem['on' + event] = callback;
}
}
Or, if you use jQuery library, you can easily normalize the whole process
$('#thing').on('click', function() {
});
source
share