Custom JavaScript Events
Jan 29, 2013     21:57:36

While working on a JavaScript plugin I decided that it is great when plugin informs user about what it have done or on what it is working right now. This functianality is the same as some events in javascript like 'click', 'keyup' or others. And the plugin should use it's own events.

But how to fire own crossbrowser event?

Here is simple answer:

1. CrossBrowser attaching events:

For attaching event to some element I wrote speciall function - addEvent.

Attributes:

  • evnt - our event keywork (like 'keyup', 'onclick');
  • func - function executed on event;

this here will be our target element.

// Funtion for adding event to some element
var addEvent = function(evnt, func) {
    if (this.addEventListener) { // W3C DOM
        this.addEventListener(evnt,func,false);
    } else if (this.attachEvent) { // IE DOM
        this.attachEvent("on"+evnt, func);
    } else { // No much to do
        this[evnt] = func;
    }
};

How to use it:

var my_element = document.getElementById('my_element_id');
addEvent.call(my_element, 'me_event', function(){
    console.log('my_event fires');
})


2. CrossBrowser firing custom JavaScript events:

And here is the function for creating custom event:

Attributes:

  • event - (String) - our event keyword;

this this here is our event target element.

function fireEvent(event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return this.fireEvent('on'+event,evt)
    } else {
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !this.dispatchEvent(evt);
    }
}

How to use it:

var my_element = document.getElementById('my_element_id');
fireEvent.call(my_element, 'my_event');

Example:

As an example we will fire custom event when button will be pressed.

var button = document.getElementById('event_test_element');
// fire our event on click
addEvent.call(button, 'click', function(){
    fireEvent.call(this, 'abra-cadabra');
})

// listen 'abra-cadabra' event
addEvent.call(button, 'abra-cadabra', function(){
    alert('abra-cadabra');
})

blog comments powered by Disqus