views:

160

answers:

1

I have been investigating event fire order between browsers, because our application is experiencing some unusual behaviour.

I have created a little test to see the order of the three events: change, keydown, and keypress.

Here is the HTML (test.html):

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"&gt;&lt;/script&gt;
        <script src="test.js"></script>
    </head>
    <body>

        <input type="text" id="TextBox" />
        <input type="button" id="Button" value="Clear Results"/>

        <hr />

        <table id="ResultTable" style="width: 100px">
            <tr><th>Results</th></tr>
        </table>
    </body>

</html>

Here is the JS (test.js):

/*
    Appends event information to display table.
*/

$(document).ready(function() {
    $("#TextBox").change(function() {
        $("<tr><td>Change</td></tr>").appendTo("#ResultTable");
    });

    $("#TextBox").keydown(function() {
        $("<tr><td>Key down</td></tr>").appendTo("#ResultTable");
    });

    $("#TextBox").keypress(function() {
        $("<tr><td>Key press</td></tr>").appendTo("#ResultTable");
    });

    $("#Button").click(function() {
        $("#ResultTable").empty();
        $("<tr><th>Results</th></tr>").appendTo("#ResultTable");
    });
});

When I type letter f into the textbox, then press enter, I get the following in Internet Explorer 8:

Results

  • Key down
  • Key press
  • Change
  • Key down
  • Key press

But in Firefox (3.6.8), I get the following:

Results

  • Key down
  • Key press
  • Key down
  • Key press
  • Change

The order of the change event is significant as we are capturing the enter key in the keydown event, but doing some validation with the change event.

I have had a look around, but haven't been able to identify where the issue is.
Is this expected behaviour? Should all browsers fire jQuery events in a specified order? Or should we remove all assumptions for order of event firing? Or is there something else that is getting in the way I am not thinking about?

A: 

I could not find anything in detail on the net about this specific scenario, other than that event order is not something that should be assumed in the implementation of browsers.

This leads me to remove the assumption that the change method will always come after onkeydown, and will have to design my validation/submit process with this consideration.

Basically I will move validation/submit into one method, and call it from both events, but make sure it is only called once, using a flag.

If anyone has any extra info/advice on this that would be great. :)

Russell