I prefer this solution:
/**
* The addEventListener() method attaches an event handler to the specified element.
* @param {*} event Type of the event (like 'load', 'click' or 'onchange' ...)
* @param {*} obj When the event occurs, an event object is passed to the function as the first parameter. The type of the event object depends on the specified event
* @param {*} fn Specifies the function to run when the event occurs.
*/
function addListener(event, obj, fn) {
if (obj.addEventListener) {
obj.addEventListener(event, fn, false); // modern browsers
} else {
obj.attachEvent("on"+event, fn); // older versions of IE
}
}
// Thge event emitter will be emitted when page is loaded
addListener('load', window, function(event) {
alert("Your page is loaded");
});
Of course, you can add more different addEventListener
, for example click
, onChange
etc.