Explain Codes LogoExplain Codes Logo

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

javascript
prompt-engineering
beforeunload
onchange
Alex KataevbyAlex Kataev·Oct 1, 2024
TLDR
window.onbeforeunload = function() { // Hey, don't leave me hanging with unsaved changes! return changesMade ? "Unsaved changes detected." : undefined; };

Exploit window.onbeforeunload to trigger this alert. If changesMade is true (indicates edits were made), return a message to prompt the user. For false, return undefined to allow no-hassle navigation.

Trapping changes in a dynamic environment

Marking modifications with the onchange event

You can detect changes by assigning an onchange event to your inputs. This event toggles changesMade to true as any modifications are detected.

var changesMade = false; // Say hello to every input, textarea, and select element! document.querySelectorAll('input, textarea, select').forEach(function(input) { input.onchange = function() { // You changed it, we noted it! changesMade = true; }; });

Safeguarding deliberate form submissions

During a form submission, we need to disable the prompt. Set this behavior by hooking it unto the onsubmit event:

// Hey form, thanks for submitting the homework! document.querySelector('form').onsubmit = function() { // You're free to navigate! window.onbeforeunload = null; };

Browser compatibility: modern vs. dinosaurs

Modern browsers might not show custom messages due to security reasons. However, they will display a default confirmation dialog. For older browsers, use the returnValue property of the beforeunload event to display a custom message.

jQuery: the knight in shining armor

For those leveraging jQuery, it provides an elegant syntax for handling beforeunload events, making cross-browser compatibility a cakewalk.

$(window).bind('beforeunload', function() { // jQuery, at your service! return changesMade ? "Unsaved changes detected." : undefined; });

Enhancements and fine tuning

Developing control methods to toggle the prompt on and off provides precise control:

function enablePrompt() { // The guard is ON duty window.onbeforeunload = ...; // define prompt logic here } function disablePrompt() { // The guard takes a break window.onbeforeunload = null; };

UX: the fussy interviewer

Clear, user-understandable confirmation messages enhance the user experience. While modern browsers default custom messages with usual dialogues, their purpose remains the same: alerting users about potential unsaved changes.

Championing compatibility across browsers

Testing with various browsers guarantees a smooth, consistent experience for your users across diverse platforms.

Document diving: Uncover treasures!

Referencing the official HTML Standard or the Mozilla Developer Network (MDN) can help you understand browser-specific behaviours, norms and constraints.