Earthling Earthling - 4 months ago 15
Javascript Question

Javascript: Adding a condition to 'Page Leave Confirmation'?

I figured out how to show a 'Are you sure you want to leave this page?' confirmation dialog if a user leaves a web page. It works. Now I need to figure out how to trigger this dialog ONLY IF the user has typed something into an input field in my page.

The following code works. But it triggers every time the user tries to leave the page:

Confirmation Listener Function:

window.addEventListener("beforeunload", function (e) {
var confirmationMessage = 'Are you sure you want to leave this page?'
+ 'We hope you had a great experience!';

(e || window.event).returnValue = confirmationMessage; //Gecko + IE

return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
});


HTML:

<input id="storyBox" type="text" />


I need to check if the user typed in any text to the input field and decide whether to trigger the leave confirmation dialog or not:

if(document.getElementById("storyBox").value.length != 0){
//Trigger the Event Listener
}


My question is, where do I place this condition? Obviously surrounding the EventListener with the condition won't work. How can I trigger this event only if the input field is not empty?

Answer

If you don't return from inside the eventListener the pop-up won't show, so you can do this:

window.addEventListener("beforeunload", function (e) {
    if(document.getElementById("storyBox").value.length != 0){
        var confirmationMessage = 'Are you sure you want to leave this page?'
                            + 'We hope you had a great experience!';

        (e || window.event).returnValue = confirmationMessage; //Gecko + IE

        return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
    }
});

Fiddle

(When you click the 'Run' button a beforeunload is raised. So you can test it.)

Comments