I am attempting to add event listeners to all of the buttons in an HTML document. When a button is pressed I'd like to display a simple alert. My code, which isn't working at the moment, follows:
var bns = document.getElementsByTagName("button");
function addtoev() {
for (i = 0; i < bns.length; i++) {
bns[i].addEventListener("click", function() {
alert("you clicked");
});
}
}
It definitely works as such in JSFiddle by calling the method or eliminating the function line, but it's still not executing in Chrome (popups are not blocked). I post my HTML, is it possible that buttons nested in a table need to be referenced differently than buttons alone?
<tr>
<td>John</td>
<td>Doe</td>
<td>[email protected]</td>
<td><button class="btn btn-default">X</button></td>
</tr>
you need to listen of the load event, like this:
function addtoev() {
var bns = document.getElementsByTagName("button");
for (i = 0; i < bns.length; i++) {
bns[i].addEventListener("click", function() {
alert("you clicked"); });
}
}
window.addEventListener("load",function() {
addtoev();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With