Maurice Snip

Weblog and Portfolio

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);
	}
}

This entry was posted on Tuesday, December 2nd, 2008 at 23:16 and is filed under Client side, Cross browser, Javascript. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “Manually firing an event the cross browser way”

  1. December 5th, 2008 at 16:11

    Ariaan.nl says:

    I think you could make shorthand notation or an try/catch solution…

  2. December 5th, 2008 at 20:02

    Maurice Snip says:

    You can indeed shorten the function, but for readability reasons I decided to go with this. Feel free to change it to your needs. :)

Leave a Reply