Craig1123 Craig1123 - 1 month ago 7
HTML Question

event.preventDefault() on multiple buttons

Is there a way to write

e.preventDefault()
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

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);
}