Archive for the ‘Cross browser’ Category
Manually firing an event the cross browser way
In a recent project I needed a way to manually fire an event that works in all major browsers on the market today. Since Internet Explorer and Firefox, Safari use a different event model, feature detection is needed. Where the document.createEvent block executes the code for Firefox, Safari, etc, the document.createEventObject executes the code for Internet Explorer. The function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | /** * Manually fires the given event * * @param {Mixed} el The element object or element ID that has to fire the event * @param {String} set The event set used, eg. HTMLEvents or MouseEvents * @param {String} type The event type to fire, eg. change or click */ function fireEventXB(el, set, type) { if(typeof el == 'string') { el = document.getElementById(el); } if(document.createEvent) { var evObj = document.createEvent(set); evObj.initEvent(type, true, false); el.dispatchEvent(evObj); } else if(document.createEventObject) { el.fireEvent('on' + type); } } |