Take the 2-minute tour ×

I have a input text that get his value from a javascript function(a timer with countdown).

I want to raise an event when the input text is 0 ,so i am using the change eventListener.

unfortunately it doesn't seem to raise the event when the change is coming from javascript function.

How can I force the change event to work, even if the change is coming from javascript and not from the user?

Thanks for any help

share|improve this question
add comment

3 Answers

up vote 7 down vote accepted

From the fine manual:

The change event occurs when a control loses the input focus and its value has been modified since gaining focus. This event is valid for INPUT, SELECT, and TEXTAREA. element.

When you modify the text input's value through code, the change event will not be fired because there is no focus change. You can trigger the event yourself though with createEvent and dispatchEvent, for example:

el = document.getElementById('x');
ev = document.createEvent('Event');
ev.initEvent('change', true, false);

And a live version: http://jsfiddle.net/ambiguous/nH8CH/

share|improve this answer
This won't work if you use any modern event listening method; it will only work if you use the old onchange property. You should use the DOM events API to fire events. –  Delan Azabani Aug 14 '11 at 8:41
@Delan: Can you tell that I haven't done raw JavaScript for a long time? I'll patch it up. –  mu is too short Aug 14 '11 at 8:45
Thanks a lot! This is so simple and working excellent! :) –  marverix Apr 15 '13 at 10:07
add comment

In the function that changes the value, manually fire a change event.

var e = document.createEvent('HTMLEvents');
e.initEvent('change', false, false);
share|improve this answer
Does it need to be HTMLEvents? The jQuery version apparently uses Event and the only difference I can see is DOM level 2 versus level 3. –  mu is too short Aug 14 '11 at 8:57
As far as I know, HTMLEvents, Event and Events are synonymous. –  Delan Azabani Aug 14 '11 at 9:01
Event seems to be the official one, Events is probably around in some browsers to match the hasFeature pluralization. –  mu is too short Aug 14 '11 at 9:10
add comment

A more reusable option :

function simulate_event(eventName, element) {
    // You could set this into the prototype as a method.
    var event;

    if (document.createEvent) {
        event = document.createEvent("HTMLEvents");
        event.initEvent(eventName, true, true);
    } else {
        event = document.createEventObject();
        event.eventType = eventName;

    event.eventName = eventName;

    if (document.createEvent) {
    } else {
        element.fireEvent("on" + event.eventName, event);
share|improve this answer
add comment

Your Answer


