Some simple event driven code. For whatever reason, I can't seem to pass 'onchange' as a parameter to fireEvent()
. Throws me an invalid argument error in IE 7/8. This project needs to be native. Little help?
Custom Event Creation:
createCustomEvent : function(eventName) {
var evt;
if(document.createEvent) {
evt = document.createEvent('CustomEvent');
evt.initEvent(eventName, true, true);
}else if(document.createEventObject) {
evt = document.createEventObject();
evt.eventName = eventName;
}
return evt;
},
dispatchCustomEvent : function (el, evt) {
if(el.dispatchEvent) {
el.dispatchEvent(evt);
}else if(el.fireEvent) {
console.log('on'+evt.eventName); //onchange
el.fireEvent('on'+evt.eventName, evt);
}
}
Usage:
dispatchCustomEvent(element, createCustomEvent('change'));
Okay, so according to most docs the change event will fire on any element and I quote: "The change event is fired when an element loses focus and its value changed since gaining focus."
https://developer.mozilla.org/en-US/docs/DOM/Mozilla_Event_Reference/change
However, in <= ie8 onchange will not fire on any element besides form elements. This is incredibly lame imo, and makes modern MVC custom event listening and dispatching an issue.
Long story short, in my case I used the blur event to capture changes to my div element. This worked for me as the focus is removed between div element updates. It's a slideshow application, where two divs pop on and off the stack, left to right depending on the current location.