Craig1123 Craig1123 - 1 year ago 71
HTML Question

event.preventDefault() on multiple buttons

Is there a way to write

once for every button on an app (perhaps by creating a function)? I understand how to prevent the default events from a button (link, etc):

<button onClick={e => e.preventDefault()} /> <!--For React, but it's the same elsewhere-->

However, I have many buttons on my app and I'm tired of writing it out for every button. Any help is appreciated :)

Answer Source

You shouldn't be using inline javascript at all, but proper event handlers

var buttons = document.querySelectorAll('button'),
    fn      = function(e) { e.preventDefault() };

for ( var i = buttons.length; i--; ) {
    buttons[i].addEventListener('click', fn, false);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download