Andrew
Andrew

Reputation: 238747

jQuery: How to bind the same action on two different events?

I find myself writing code that looks something like this:

$(document).ready(function(){

    updateStuff();

    $('select').change(function(){
        updateStuff();
    });
});

function updateStuff(){
    //do something simple
}

The same function updateStuff() is called twice (once for each event), but nothing is different between the two events. I am wondering if there is a better way to write this so that the same code is called on both events, and I can dry up my code even more. That way, I won't need to create this function in the first place.

Maybe something like this (if such a syntax exists)?

$('select').bind(['document.ready', 'change'], function(){
    //do something simple
});

Upvotes: 2

Views: 1242

Answers (2)

Ender
Ender

Reputation: 15221

You need to have the change event binding inside of the ready handler, so that the DOM is guaranteed to be ready for manipulation when you do the binding. You are doing it in almost the simplest possible way that I can think of. I would change your code to bind your change event like so:

$('select').change(updateStuff);

Unless you need to pass in parameters, there's no need to wrap your call to updateStuff() in an anonymous function.

As jAndy points out, you can also invoke the function you've bound as an event handler by manually invoking the event's handlers with jQuery, like so:

$('select').change(updateStuff).change();

You could also be using the shorthand ready binding, so your code would then be simplified down to this:

$(function(){
    $('select').change(updateStuff).change();
});

function updateStuff(){
    //do something simple
}

However, if you wanted to bind to other events (other than ready) at the same time, you could do it like so:

$('select').bind('change click', updateStuff);

Have a look at the documentation for .bind() here

Upvotes: 2

jAndy
jAndy

Reputation: 236022

$(document).ready(function() {
    $('select').change(function(){
        updateStuff();
    }).change();
});

..is probably the most convinient way to achieve this. It's like, "bind the change event to that node and then call that event handler once at least".

Or even shorter:

$(document).ready(function() {
    $('select').change( updateStuff ).change();
});

Upvotes: 1

Related Questions