javascript 16 lines · 5 steps

Warn before leaving a form with unsaved edits

Track whether a form has unsaved changes and prompt the user before they navigate away.

Explained by highlit
1const form = document.querySelector('#profile-form');
2let isDirty = false;
3 
4form.addEventListener('input', () => {
5 isDirty = true;
6});
7 
8form.addEventListener('submit', () => {
9 isDirty = false;
10});
11 
12window.addEventListener('beforeunload', (event) => {
13 if (!isDirty) return;
14 event.preventDefault();
15 event.returnValue = '';
16});
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A single boolean flag is enough to track whether a form has unsaved state.
  2. 2The beforeunload event lets you intercept navigation, but only shows a generic browser prompt.
  3. 3Reset your dirty flag on submit so a successful save doesn't trigger the warning.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Warn before leaving a form with unsaved edits — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code