Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery same function for multiple elements and multiple events

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.

like image 598
Toni Perić Avatar asked Oct 08 '13 20:10

Toni Perić


People also ask

Can we use two events together in jQuery?

The jQuery . on() can attach multiple events on an element. In the below code I have attached 2 events to the p element. So when the element is clicked or mouse leaves this element, you will get alert box displayed.

Can we handle multiple events on a single HTML element using jQuery?

In jQuery, we can add one or more than one event handler on any element easily.

Can we use multiple selectors in jQuery?

jQuery - Multiple Elements SelectorYou can specify any number of selectors to combine into a single result.

How do I pass multiple events in Javascript?

JQuery's bind allows multiple events, like so: $(window). bind('mousemove touchmove', function(e) { //do something; });


2 Answers

You don't have to make your function inline.

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

$('.element').on('click', doStuff);
$('select').on('change', doStuff);
like image 161
Kippie Avatar answered Sep 28 '22 18:09

Kippie


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.

like image 22
Jacob Mattison Avatar answered Sep 28 '22 20:09

Jacob Mattison