JQuery function for multiple items and multiple events

I have a function that I would like to do whenever the user clicks on one of the anchor elements, for example

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

and I want to do the same if the select element changed its value, for example

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

I know what I could do

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

but it also works whenever I click on the select element, and I don't want to confuse the user and do something only when the value of the select element has changed.

+4
source share
2 answers

You have to make your function built-in.

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

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

- :

function doStuff(){
 //do stuff here
}

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

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

, , .

+7

All Articles