Create a javascript function for all application buttons

Asked

Viewed 25 times

1

Guys, I would like to create a javascript function for all the buttons of the application, IE, every button when it is clicked it will call this function.

Note: No need to put the onclick on each button.

Thank you!!

  • @Eliseub. One of the answers (this one) does not use jQuery.

1 answer

1


var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i < buttonsCount; i += 1) {
    buttons[i].onclick = function(e) {
        alert(this.id);
        // O que quer que ele faça
    };
}
button {
padding: 10px;
font-size: 13px;
}
<button id='1'>Clique</button>
<button id='2'>Clique</button>
<button id='3'>Clique</button>
<button id='4'>Clique</button>

  • 1

    Solved my problem, thank you!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.