Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
Event listener in HTML vs. addEventListener

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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)">
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!