3

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:

  • Why does it appear to work differently for submit vs click?
  • Why does the anchor's click handler only get executed twice and not indefinitely, if the event handler is being executed each time it's called?
6
  • In a simple test I made, the submit is executed indefinite times. May there's an error in this.click() Commented Jun 6, 2022 at 7:12
  • @StavNoy By the standard the submit event must not fire when submitted by the submit method of the form (item 6 in the submit algorithm). If you're using ex. jQuery's submit method, then the submit listener will be fired. Commented Jun 6, 2022 at 7:15
  • @Teemu not with the evt.preventDefault(). Here's an example where it works: stackblitz.com/edit/web-platform-c55t7j?file=index.html Commented Jun 6, 2022 at 7:27
  • @StavNoy Your code snippet doesn't use the submit method of the form. Commented Jun 6, 2022 at 7:31
  • addEventListener('submit') ? Unless you mean form.onsubmit = ... or <form onsubmit="...", but the question uses addEventListener (and my guess is they're all the same in this case) Commented Jun 6, 2022 at 7:45

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.