JavaScript custom Event Listener

Lpc_dark picture Lpc_dark · Mar 12, 2012 · Viewed 80.2k times · Source

I was wondering if anyone can help me understand how exactly to create different Custom event listeners.

I don't have a specific case of an event but I want to learn just in general how it is done, so I can apply it where it is needed.

What I was looking to do, just incase some folks might need to know, was:

var position = 0;

for(var i = 0; i < 10; i++)
{
    position++;
    if((position + 1) % 4 == 0)
    {
        // do some functions
    }
}

Answer

Max picture Max · Apr 10, 2012
var evt = document.createEvent("Event");
evt.initEvent("myEvent",true,true);

// custom param
evt.foo = "bar";

//register
document.addEventListener("myEvent",myEventHandler,false);

//invoke
document.dispatchEvent(evt);

Here is the way to do it more locally, pinpointing listeners and publishers: http://www.kaizou.org/2010/03/generating-custom-javascript-events/