Home > OS >  Event listener in HTML vs. addEventListener
Event listener in HTML vs. addEventListener

Time:11-16

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.

CodePudding user response:

Use the first version - but dont use querySelectorAll if you only have one form. If you have only one form, give it an ID and use document.getElementById instead.

If you have many, I would delegate:

<div id="formContainer">
  <form class="my-form">
    <input type="submit"/>
  </form>
  <form class="my-form">
    <input type="submit"/>
  </form>
</div>
<script>
  document.getElementById("formContainer").addEventListener("submit", function(e) {
    e.preventDefault();
    console.log("Data received");
  });

</script>

To do the second, we used to do this in the previous millenium

<form onsubmit="return doSomething()">
  <input type="submit"/>
</form>
<script>
  function doSomething() {
    console.log("Data received");
    return false
  }
</script>

but it is not recommended

CodePudding user response:

In the second case you're calling doSomething() with no argument, so e will be undefined. You need to pass the event as an argument explicitly:

<form onsubmit="doSomething(event)">
  • Related