Event handlers for all types of buttons

I want to provide a function that will listen for all button click events.

A web developer can use different buttons.

<button></button>

      

or

<input type="button"></input>

      

or

<div class="button"></div>

      

and etc.

Is there a way to add a common event handler for all these different types of buttons? I would like to avoid manually writing event handlers for all possible ways to create a button.

EDIT: Many of you have posted a good solution for creating a generic class, but unfortunately I am not the one who creates the buttons, I provide a function that the app / site developer will call and I will collect all types of button click events and send them to the server ...

+3


source to share


3 answers


One possible way is to add common class

to all topics elements

:

 <buttonclass="btn"></button>
   <input type="button" class="btn"></input>
   <div class="button btn"></div>

      



Then listen to these elements with this class:

$('.btn').on('click', function(){
 //Your code
})

      

+1


source


$(':button, .button').on('click', function() {
    // Event handler code
});

      

I would recommend that you use a generic class for all types of buttons and add the event using the class:



<button class="myButton"></button>
<input type="button" class="myButton"></input>
<div class="button"></div>


$('.myButton').on('click', function() {
    // Event handler code
});

      

+1


source


If you created a click event handler like:

$('.btn-click').click(function() {
    alert('Hello World');
});

      

Then you can add this event to several different tags by simply giving it a class btn-click

.

<button class="btn-click"></button>

<input type="button" class="btn-click"></input>

<div class="button btn-click"></div>

      

Working JS Fiddle: http://jsfiddle.net/VDesign/gvjLLf9L/

+1


source