10.04.04

Custom Javascript Events

Posted in Uncategorized at 10:37 am by UnwashedMeme

One has the capacity to create and fire custom events in Javascript, but I was
unable to find a quick introduction, so here is my example.

function fireEvent(name, target) {
	//Ready: create a generic event
	var evt = document.createEvent("Events")
	//Aim: initialize it to be the event we want
	evt.initEvent(name, true, true); //true for can bubble, true for cancelable
	//FIRE!
	target.dispatchEvent(evt);
}

function foobar() {
	alert("foobar");
}

function testEvents() {
	window.addEventListener("foobar", foobar, false); //false to get it in bubble not capture.
	fireEvent("foobar", document);
}
		

Some references:

3 Comments »

  1. Eirikur Hrafnsson said,

    May 26, 2007 at 9:38 am

    Thanks alot been looking for exactly this info myself!

  2. Alex Egg said,

    July 4, 2007 at 7:20 pm

    Your using addEventListener which doesn’t work in IE.

  3. Alex Egg said,

    July 4, 2007 at 7:32 pm

    createEvent is non IE too

Leave a Comment