max max - 2 months ago 23
Javascript Question

Jquery: bind load + change simultaneously

In many cases, I need to bind a behaviour to an element after loading, and then after an event triggering (like "change").
I think the best way would be to make it in the same line:

$('#element_id').bind('load, change', function () {
...
});


But this works only for "change" and not for "load". There is a better way?

Answer

I stumbled across the same problem. Removing comma is not enough, at least not in this case:

$(document).ready(function(){
    $('#element_id').bind('load change', function () {
        ... // (this DOESN'T get called on page load)
    });
});

I guess load events get triggered before $(document).ready().

This is a simple solution:

$(document).ready(function(){
    $('#element_id').bind('change', function () {
        ...
    });
    $('#element_id').trigger('change');
});