Ben J. Christensen

Software Development and Other Random Stuff

Trigger Native Javascript Events with Prototype.js

After much searching and playing with various solutions, I found one at this page:

http://stackoverflow.com/questions/590289/javascript-event-that-fires-without-user-interaction/590339#590339

This provides an easy method for programmatically invoking native events such as “onchange”.

Here it is:


// this supports trigger native events such as 'onchange' 
// whereas prototype.js Event.fire only supports custom events
function triggerEvent(element, eventName) {
    // safari, webkit, gecko
    if (document.createEvent)
    {
    var evt = document.createEvent('HTMLEvents');
    evt.initEvent(eventName, true, true);</code>

        return element.dispatchEvent(evt);
    }

    // Internet Explorer
    if (element.fireEvent) {
        return element.fireEvent('on' + eventName);
    }
}

This is primarily to deal with prototype.js not allowing the firing of native events (which jQuery does).

Here is another approach I found but have not tried which adds the capability to prototype.js: event.simulate.js

Advertisement

Filed under: Code

4 Responses

  1. Mubbashir says:

    And this is the world where Selenium lives and Rules :D

  2. [...] I found was a nice post by Ben Christensen talking about this exact problem. The code on his page creates a function that will trigger events [...]

  3. jazkat says:

    Thanks for your post. I’d just add how to call the function:

    // in prototype:
    triggerEvent($(‘someElementId’),’change’);

    // in js:
    triggerEvent(document.getElementById(‘someElementId’), ‘change’);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Twitter Updates

View Ben Christensen's profile on LinkedIn
Follow

Get every new post delivered to your Inbox.