6

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.

2 Answers 2

23

You don't have to make your function inline.

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

$('.element').on('click', doStuff);
$('select').on('change', doStuff);
Sign up to request clarification or add additional context in comments.

Comments

7

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.

4 Comments

Kippie's answer is strictly better than this one.
Why call doStuff inline? This way your function's scope will be lost, and this will be global, rather than the calling element.
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.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.