If I have the following event handler bound to my form:
form.addEventListener('submit', function(evt) {
evt.preventDefault();
console.log('submitted');
this.submit();
});
When the form is submitted by the client, the event handler is executed and the form is submitted without the event handler being executed again.
However, the same logic doesn't apply when attaching click handlers to anchor elements:
a.addEventListener('click', function(evt) {
evt.preventDefault();
console.log('clicked');
this.click();
});
The event handler is executed twice and the link is never followed.
I have two questions:
submit vs click?click handler only get executed twice and not indefinitely, if the event handler is being executed each time it's called?Form submission and element click are different actions, they don't have to behave in the same way.
When using the submit method of the form, the standard says:
Submits the form, bypassing interactive constraint validation and without firing a submit event.
This can be seen also in the submission algorithm. Item 6 checks, whether the action comes from the submit method of the form, and skips the validation and event firing if the "submit()" flag is set.
element.click sets "click in progress flag", which is checked internally before creating a syntehtic click event which calls the hander function. This prevents a click on an element to lead to infinite recursive click event handler calls.