Reputation: 5074
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?
Upvotes: 1
Views: 166
Reputation: 2795
var confirmMessage = 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.
};
function bindEvent(element){
if(document.getElementById("storyBox").value.length != 0){
window.addEventListener("beforeunload", confirmMessage);
}
else {
window.removeEventListener("beforeunload", confirmMessage);
}
};
This will also work. This remove the eventListener when no text in the input. and add the eventListner there are text inside the text box
Upvotes: 1
Reputation: 644
this code is simple but it will work
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = 'Are you sure you want to leave this page?'
+ 'We hope you had a great experience!';
if(document.getElementById("storyBox").value.length != 0){
return confirmationMessage;
}
});
Upvotes: 1
Reputation: 7145
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.
}
});
(When you click the 'Run' button a beforeunload
is raised. So you can test it.)
Upvotes: 3