Search code examples
jquerytwitter-bootstrapbootstrap-switch

Multiple jquery events with same execution - how to combine?


I've found many threads on combining click and change jquery events. But I'm not sure how to combine a basic click event with this specific event for Bootstrap Switch. The following two events should have the same code. What is the best way to combine them, so I don't have repeat the same code twice?

1.

$('#regular-product .cancel').click(function(e){

   // SAME CODE GOES HERE //

});

2.

$('#regular-product .toggle').on('switchChange.bootstrapSwitch', function(event, state) {

    if ($('#regular-product .bootstrap-switch').hasClass('bootstrap-switch-off')) {

      // SAME CODE GOES HERE //

    }       
});

Here is an answer I found that I wasn't able to repeat for this. (Jquery combine click and change for one execution) Perhaps it's not the right method in this case?


Solution

  • Wrap your code into a function.

    E.g.:

    var myHandler = function()  {
      // do here some stuff you want to
    };
    $('#regular-product .cancel').click(myHandler);
    $('#regular-product .toggle').on('switchChange.bootstrapSwitch', myHandler);