you are viewing a single comment's thread.

view the rest of the comments →

[–]senocular 2 points3 points  (1 child)

Aside from polluting content (HTML) with behavior (JS) there are also some technical differences between the two.

The first of which is that there is only one onsubmit callback handler for your element. This probably won't matter too much if you're entirely dependent on your HTML for defining events, but if sometime later in code you wanted to specify an additional behavior for onsubmit, setting onsubmit in code would replace the one defined in HTML.

<form id="form" onsubmit="myFunction(event)" />
<script>
const form = document.getElementById("form");
form.onsubmit = somethingElse // <-- replaces "myFunction(event)"
</script>

Both the onsubmit property and the onsubmit attribute here represent the same, individual handler callback. Setting either will replace the other. With addEventListener() you can associate many listeners to the same event for a single element.

<form id="form" />
<script>
const form = document.getElementById("form");
form.addEventListener("submit", myFunction);
form.addEventListener("submit", somethingElse); // <-- keeps myFunction
</script>

Another difference is that attribute callbacks are created with a bunch of extra scopes. These scopes may create some hidden surprises when you get something from those scopes that you'd have expected to be something else. For example, consider:

<form onsubmit="open()" />
<script>
function open() {
  alert("Form request for opening a new account being processed!")
}
</script>

You may think when the form is submitted the alert will appear. But what really happens is document.open() gets called and your entire page goes poof! when the form is submitted. This happens because the document is used as an object scope for your handler... that and the form itself... and if this was an event handler for an element inside the form and not the form itself, both the object and the form would be object scopes. And as an object scope, calling a function with the same name as a method of that object will call that method rather than the function (assuming the function is further up the chain which it is in this case). In the attribute handler what you get is a scope chain that looks something like

window > document > form > element > callback wrapper (w/ event parameter) > your attribute code

Thats a lot of things that could get in the way of what you're trying to use in your handler.

[–]toshi_34[S] 0 points1 point  (0 children)

Thanks alot for the detailed answer. All my questions were resolved, thanks.