I want to add an event listener to an HTML element which replaces the default behavior by custom behavior. I know two different ways of adding event listeners: (1) use the JavaScript function addEventListener
to add an event to a DOM element:
<form class="my-form">
<input type="submit"/>
</form>
<script>
document.querySelectorAll(".my-form").forEach(form => {
form.addEventListener("submit", doSomething);
});
function doSomething(e) {
e.preventDefault();
console.log("Data received");
}
</script>
(2) use the HTML attributes on*
:
<form onsubmit="doSomething()">
<input type="submit"/>
</form>
<script>
function doSomething(e) {
e.preventDefault();
console.log("Data received");
}
</script>
However, the first one does what it should do, the second one doesn't. The second code still uses the default submit handler. So, I'm wondering whether the behavior of the first example can be achieved with HTML attributes. And besides, I would like to know which way of adding event handlers is generally preferred.