jQuery same function for multiple elements and multiple events

19,129

Solution 1

You don't have to make your function inline.

var doStuff = function() {
  // do stuff here
});

$('.element').on('click', doStuff);
$('select').on('change', doStuff);

Solution 2

One of the most readable ways to handle this is to create a separate function:

function doStuff(){
 //do stuff here
}

$('.element').on('click', function(){
  doStuff();
});

$('select').on('change', function(){
  doStuff();
});

This also gives you a lovely opportunity to make it more clear what your code is for, by giving that function a nice, meaningful name.

Share:
19,129
Toni Perić
Author by

Toni Perić

Updated on June 04, 2022

Comments

  • Toni Perić
    Toni Perić about 2 years

    I have a function I'd like to do whenever either user clicks one of the anchor elements, such as this

    $('.element').on('click', function(){
    // do stuff here
    });
    

    and I want to do the same thing if a select element has changed its value, such as this

    $('select').on('change', function(){
    // do same stuff here
    });
    

    I know I could do

    $('.element', 'select').on('click change', function(){
    // do stuff here
    });
    

    but that would also trigger whenever I click on the select element and I don't want to confuse user and do something then, just when the select element value has changed.

  • Ryan Kinal
    Ryan Kinal over 10 years
    Kippie's answer is strictly better than this one.
  • Kippie
    Kippie over 10 years
    Why call doStuff inline? This way your function's scope will be lost, and this will be global, rather than the calling element.
  • Jacob Mattison
    Jacob Mattison over 10 years
    Yeah, in most cases it's better to take Kippie's approach (pass in a function rather than calling it). I wanted it to be clearer to the OP what's going on, and to give them the opportunity to do other things in each case, in case there are differences they didn't mention. Baby steps. I won't change my answer, but yeah, read my answer to make sure you understand what's happening, but actually do it like Kippie did.
  • Durian Nangka
    Durian Nangka over 4 years
    As a relative newbie to these matters, I'm wondering if Jacob Mattison's approach is the way to go if you actually want to pass an argument to the doStuff function when the event occurs?