I possess a set of functions that allow me to configure prompts for when someone exits a page while inputting values. However, my main concern lies in how to properly encapsulate the checkFlag
. Currently, checkFlag
is being treated as a global variable which proves to be somewhat inconvenient.
let checkFlag = false;
const onBeforeunloadHandler = function(e) {
var msg = '';
e.returnValue = msg;
};
const formAlert = function() {
if(!checkFlag) {
window.addEventListener('beforeunload', onBeforeunloadHandler);
for(var i = 0; i < checkValue.length; i++) {
checkValue[i].removeEventListener('input', formAlert);
checkValue[i].removeEventListener('change', formAlert);
}
checkFlag = true;
}
};
(() => {
let checkValue = document.querySelectorAll( "input[form='test'], textarea[form='test']");
let submitBtn = document.querySelector('button[type="button"]');
for(var i = 0; i < checkValue.length; i++) {
checkValue[i].addEventListener('input', formAlert);
checkValue[i].addEventListener('change', formAlert);
}
submitBtn.addEventListener('click', function() {
window.removeEventListener('beforeunload', onBeforeunloadHandler);
});
})();
If you have any suggestions or feedback, please don't hesitate to share. Thank you!