TIL: How To Properly Dispatch A Submit Event.

A submit event is not sent to the form when calling the form.submit() method directly.

Jim Remsik
By Jim Remsik
March 19, 2021

We have been building a Responsive Web Chat application. In order to provide users with a look and feel similar to a native app we decided to include page transition animations using the CSS and Javascript frameworks in our application, TailwindCSS and StimulusReflex.

At the same time a visual design change caused the submit button to be placed outside of the form. We therefore needed to trigger the submit programmatically using Javascript.

this.element.addEventListener('click', (event) => {
  event.preventDefault();
  this.form.submit());
})

This worked when we were relying on a controller POST submit and page refresh. However, once we moved our form submission and animation into a Reflex to our surprise no submit event seemed to be triggered and our Reflex was not being called. Curious!

After some googling, we discovered that form.submit() does not trigger a submit event to be dispatched. Instead of using form.submit() we chose to explicitly dispatch the submit event our Reflex was expecting and now we have a polished user interaction that feels a little closer to native.

this.element.addEventListener('click', (event) => {
  event.preventDefault();
  this.form.dispatchEvent(new Event('submit'));
})

If you’re looking for a team to help you discover the right thing to build and help you build it, get in touch.