Skip to content

Instantly share code, notes, and snippets.

@brianlmoon
Created January 27, 2014 17:23
Show Gist options
  • Save brianlmoon/8653141 to your computer and use it in GitHub Desktop.
Save brianlmoon/8653141 to your computer and use it in GitHub Desktop.
Block Mac navigation when form has changed
function blockLeaving (e){
if(e.metaKey && (e.keyCode == 39 || e.keyCode == 37)){
switch(document.activeElement.tagName){
case "INPUT":
case "TEXTAREA":
break;
default:
if(!window.confirm("You have unsaved changes. Are you sure you want to leave the page?")){
e.preventDefault();
}
return false;
}
}
}
function detectChange (e){
if(!this.fired){
document.body.addEventListener("keydown", blockLeaving);
this.fired = true;
}
}
var formElements = document.querySelectorAll("input, textarea, select, button");
for(var n=0; n < formElements.length; n++){
switch(formElements[n].tagName){
case "INPUT":
case "TEXTAREA":
formElements[n].addEventListener("input", detectChange);
break;
case "SELECT":
formElements[n].addEventListener("change", detectChange);
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment