jQuery .change() event is triggered with .click() in newer versions?

Jared Cobb picture Jared Cobb · Jun 14, 2011 · Viewed 29.3k times · Source

I'm currently upgrading my application to use jQuery 1.6.1 (previously using 1.4.4) and found that now the .click() event automatically triggers a .change() event as well.

I created a simple example here: http://jsfiddle.net/wDKPN/

Notice if you include 1.4.4 the .change() function will not fire when the .click() event is triggered. But when switching to 1.6, the .change() event is fired when .click() is triggered.

Two questions:

  1. Is this a bug? It seems that programmatically triggering .click() shouldn't also fire other events (for example, it would seem wrong to also automatically fire .blur() and .focus(), to help "mimic" a user's click).

  2. What is the proper way for me to bind a change() event and then trigger both a click() and change() event for that element? Do I simply call .click(), and rely on the fact that .change() will also fire?

    $('#myelement').change(function() {
         // do some stuff
    });
    
    $('#myelement').click(); // both click and change will fire, yay!
    

In my old code I'm using this pattern to initialize some checkboxes (and their checked states and values) after an ajax call:

    $('#myelement').change(function() {
         // do some stuff including ajax work
    }).click().change();

But in 1.6.1 my logic fires twice (once for .click() and once for .change()). Can I rely on just removing the .change() trigger and hope that jQuery continues to behave this way in future versions?

Answer

Shef picture Shef · Jun 15, 2011

Best way to do this is:

$('#myelement').bind('initCheckboxes change', function() {
     // do some stuff including ajax work
}).trigger('initCheckboxes');

To do your initialization stuff you just bind to it a custom event, which you trigger it the first time the page loads. This, no one will take away from you on any versions.

Whereas change event, I believe, will continue to be there on all versions, because it has been for so long, and it just works nicely that way.

In the end, this is a happy ending story, because the custom event initCheckboxes will fire just once on page load and change event will always listen and fire on change state.