0

I wanted to ask if it makes a difference where I call my function. For example when submitting a form, what is the preferred / better way?

1:

<form id="registerForm" action="javascript:register()">
   <label for="user">Username</label>
   <input id="user" name="user" type="text" />
   ...
   <button>Register</button>
</form>

Or

const registerFormElement = document.querySelector("#registerForm");
registerFormElement.addEventListener("submit", (e) => {
  // some code ...
});

I always used the second approach, but i saw on github that some people use the first code example.

Ayhan
  • 51
  • 5
  • 1
    Second one is considered cleaner – MuFFes Jul 24 '22 at 16:49
  • Does this answer your question? [What is the purpose of the html form tag](https://stackoverflow.com/questions/31066693/what-is-the-purpose-of-the-html-form-tag) – jmargolisvt Jul 24 '22 at 16:54
  • No, it's not about the `form` tag. I just used it as an example. I could've also used the `a` tag with `onclick` – Ayhan Jul 24 '22 at 17:00
  • 2
    Use whatever works for you. But you can make your life easier with a concept known as [_"separation of concerns"](https://en.wikipedia.org/wiki/Separation_of_concerns)_ -> separate markup and JavaScript. With that your site will also work when the viewer has disabled JavaScript. – Andreas Jul 24 '22 at 17:00

1 Answers1

-2

The first approach is easier to understand for beginner. But the second approach is much prefered way for production code.

For production code (on real websites), we generally use obfuscation and minification, which can replace the function name to reduce JS script file size. (e.g.: register function name would be replaced to r after obfuscation and minification).

Hence, it is always better to use second approach.

Ashok
  • 2,411
  • 1
  • 13
  • 23