Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript, add event listener to all buttons [duplicate]

Tags:

javascript

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> 
like image 962
eabates Avatar asked Nov 26 '25 21:11

eabates


1 Answers

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();
});
like image 91
nloomans Avatar answered Nov 29 '25 11:11

nloomans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!