When I was talking about Async, Ajax, and animation, I mentioned the little trick I’ve used of generating a progress
element to indicate to the user that an Ajax request is underway.
I sometimes use the same technique even if Ajax isn’t involved. When a form is being submitted, I find it’s often good to provide explicit, immediate feedback that the submission is underway. Sure, the browser will do its own thing but a browser doesn’t differentiate between showing that a regular link has been clicked, and showing that all those important details you just entered into a form are on their way.
Here’s the JavaScript I use. It’s fairly simplistic, and I’m limiting it to POST requests only. At the moment that a form begins to submit, a progress
element is inserted at the end of the form …which is usually right by the submit button that the user will have just pressed.
While I’m at it, I also set a variable to indicate that a POST submission is underway. So even if the user clicks on that submit button multiple times, only one request is set.
You’ll notice that I’m attaching an event to each form
element, rather than using event delegation to listen for a click
event on the parent document and then figuring out whether that click
event was triggered by a submit button. Usually I’m a big fan of event delegation but in this case, it’s important that the event I’m listening to is the submit
event. A form won’t fire that event unless the data is truly winging its way to the server. That means you can do all the client-side validation you want—making good use of the required
attribute where appropriate—safe in the knowledge that the progess
element won’t be generated until the form has passed its validation checks.
If you like this particular pattern, feel free to use the code. Better yet, improve upon it.