Update Panel .NET

Exploring Microsoft ASP.NET AJAX and jQuery

jQuery fireEvent plugin

with 3 comments

I needed a way to simulate the “change” DOM event for input elements, so I created this plugin:

$.fn.fireEvent = function(eventType) {
    return this.each(function() {
        if (document.createEvent) {
            var event = document.createEvent("HTMLEvents");
            event.initEvent(eventType, true, true);
            return !this.dispatchEvent(event);
        } else {
            var event = document.createEventObject();
            return this.fireEvent("on" + eventType, event)
        }
    });
};

Usage:

$("#field").fireEvent("change");

When I have time, I’ll explain the reason why I needed to use this plugin instead of just $(“#field”).change()!


Written by tzkuei

July 9, 2009 at 9:24 am

Posted in JavaScript

3 Responses

Subscribe to comments with RSS.

  1. Bless you. I’ve been looking for a way inside of jQuery to call dispatchEvent on a selected item. This works perfectly.

    Brian

    March 11, 2010 at 2:38 am

  2. Hello, special thanks – this works perfectly.

    I use this in FF with Greasemonkey and jQuery to perform click Events. Works perfect, i’m happy ;) !!

    toc

    June 13, 2010 at 6:36 am

  3. I have added an optional param to allow to edit the event object before firing it, eg. using it like:

    $(“#field”).fireEvent( “keyup”, {keyCode:13} );

    This would fire the release of the return key. Here is the code:

    $.fn.fireEvent = function(eventType, properties)
    {
    var e = function(a, b)
    {
    for(var p in b)
    {
    a[p] = b[p];
    }
    return a;
    };

    if( ! properties ){
    properties = {} ;
    };

    return this.each(function()
    {
    if (document.createEvent)
    {
    var event = document.createEvent(“HTMLEvents”);
    event.initEvent(eventType, true, true);
    event = e(event, properties);
    return !this.dispatchEvent(event);
    }
    else
    {
    var event = document.createEventObject();
    event = e(event, properties);
    return this.fireEvent(“on” + eventType, event);
    }
    });
    };

    loubregand

    July 14, 2010 at 4:35 pm


Leave a Reply