Wednesday, March 13, 2019

JavaScript: Internet Explorer Event Handling


This is for event handling on different IE versions.

Dispatch an event at a specific element:

if (elemnt.dispatchEvent) {
  // IE9 and up
  var evtObj = document.createEvent('MouseEvents');
  evtObj.initEvent(event, true, true);
  elemnt.dispatchEvent(evtObj, true, true);
} else if (elemnt.fireEvent) {
  // Old versions of IE
  elemnt.fireEvent('on' + event);
}

Add the event listener for an element:

function myFunc() {
  // do something
}

if (elemnt.addEventListener) {
  // IE9 and up 
  elemnt.addEventListener(event, myFunc);
} else if (elemnt.attachEvent) {
  // Old versions of IE
  elemnt.attachEvent('on'+event, myFunc);
}

No comments:

 
Get This <