Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 650
max Avatar asked Sep 23 '11 15:09

max


2 Answers

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');
});
like image 118
johndodo Avatar answered Oct 13 '22 16:10

johndodo


For already loaded content, when you want to run a function on an event and also straight away, you can use a custom event of your own naming to avoid triggering any existing bindings from libraries etc. on the built in events, e.g.

$(".my-selector").on("change rightnow", function() {
  // do stuff...
}).triggerHandler("rightnow");
like image 35
stovroz Avatar answered Oct 13 '22 15:10

stovroz