call the same jQuery function in multiple buttons

First solution :

function doClick(e) { 
   $('#modal').reveal({ 
     animation: 'fade',
     animationspeed: 150,
     closeonbackgroundclick: true, 
     dismissmodalclass: 'close'
   });
   return false;
}
$('#button1').click(doClick);
$('#button2').click(doClick);

Second solution :

Give a class “someClass” to all the involved buttons

<input type=button class=someClass ...

and do

$('.someClass').click(function(e) { 
...
});

Third solution :

Use the comma to separate ids :

$('#button1, #button2').click(function(e) { 
...
});

Generally, the best solution is the second one : it allows you to add buttons in your code without modifying the javascript part. If you add some of those buttons dynamically, you may even do

$(document).on('click', '.someClass', function(e) { 
...
});

Leave a Comment