max2020 max2020 - 25 days ago 8
Javascript Question

Javascript jQuery multiple buttons and click events

I am putting something together which has lots of buttons and each button does a different thing.

The way I've done it is like this:

$( "#somebutton" ).click(function() {
//Do something
});

$( "#someotherbutton" ).click(function() {
//Do something else
});

$( "#someotherbutton" ).click(function() {
//Do something else
});

$( "#someotherbutton" ).click(function() {
//Do something else
});


...and so one...

My question is...

Is there a better way to do this for example having an array with button id's and this calling functionsafter the click event?

Answer Source

If you stored the buttons and their corresponding click callback functions in an array/object structure, you could compact this and then make a generic function to invoke each at the right time:

$( "button" ).click(function(evt) { 
    // this binding is lost inside of forEach
    var id = this.id;
    // Loop over each stored object in the array...
    var result = buttonsAndFunctions.forEach(function(obj){
      // If the current object.button matches the button.id, invoke the function
      // Since the function won't directly recieve the event, we'll pass the event
      // to the function:
      (obj.button === id) ? obj.fn(evt) : "";
    });
});


var buttonsAndFunctions = [
  // I'm using the same function for each button here only for demonstration
  // In reality, they'd each be different
  { button : "btn1", fn : function(evt){ console.log(evt.target.id + " was clicked"); } },
  { button : "btn2", fn : function(evt){ console.log(evt.target.id + " was clicked"); } },
  { button : "btn3", fn : function(evt){ console.log(evt.target.id + " was clicked"); } },
  { button : "btn4", fn : function(evt){ console.log(evt.target.id + " was clicked"); } }
]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>
<button id="btn3">Button 3</button>
<button id="btn4">Button 3</button>