JQuery assign events to buttons
buttonclick, javascript, jquery, onclick, onclicklistener
Solution
Event listeners cost memory. You have to think carefully about how you should implement the listeners.
1. The straightforward way:
Do not use this
If the behaviour for each button is the same, use a class:
$(".btn").click(function() {
// Do something
});
If behaviour for each button is different, assign events to different #IDs
$("#btn1").click(function {
// Do something
});
2. Use .on():
jQuery 1.7 introduced .on() method that wraps all listeners to 1 method.
$("button").on("click", function() {
// Do something
});
However, we are still binding many listeners on the page.
3. Use a wrapper (use this!):
Wrap your buttons with a div and create one listener for it.
$("#wrapper").on("click", "button", function() {
// Do something
});
Useful resources:
- Performance comparison
- .on()
Problem
I have 50 dynamically generated HTML buttons as follows: ``` <input type="button" id="btn1" name="myButton" value="Click Me" /> <input type="button" id="btn2" name="myButton" value="Click Me" /> : : : <input type="button" id="btn50" name="myButton" value="Click Me" /> ``` Which is the best way to assign click event to all buttons using jQuery? By using `id` or by using `name` attribute ?