Skip to content

Instantly share code, notes, and snippets.

@johnantoni
Created August 19, 2010 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnantoni/537728 to your computer and use it in GitHub Desktop.
Save johnantoni/537728 to your computer and use it in GitHub Desktop.
determine if element changed inside iframe and create alert on clicking exit element
/*
* jquery.tamperframe.js
* v 0.1
*
* Initial Author
* John Griffiths
*
* Description
* Simpy watches an element for changes, if any encountered flips the flag.
* If the exit button is clicked and the flag is true a dialog appears warning user will lose changes.
*
* Params:
* watchName : element (textarea) to watch for changes
* exitName : element (button) which classes as an exit when clicked
* messageText : text to show in the alert dialog
* watchFrame : if defined, check for watchName inside iframe of watchFrame
*/
jQuery.tamperFrame = function(watchFrame, watchName, exitName, messageText) {
// init
var watchIfr = $(watchFrame);
var watchEl = watchIfr.eq(0).contents().find(watchName);
var exitEl = $(exitName);
messageText = messageText || "Are you sure? \nDoing so will lose any pending changes."; // default text
// begin
if (watchEl.length > 0) {
// store arguments inside elements
watchEl.data('altered', false);
exitEl.data('tamper', { frame: watchFrame, watch: watchName, message: messageText});
// watch any keystrokes, flip flag
watchEl.keypress(function() {
$(this).data('altered', true);
});
// on clicking exit element, if tampered with, throw alert
exitEl.click(function() {
var returnVal = true;
var frame = $(this).data('tamper').frame;
var watch = $(this).data('tamper').watch;
var el = $(frame).eq(0).contents().find(watch);
var flag = $(el).data('altered') || false;
if (flag) {
var msg = $(this).data('tamper').message;
if (confirm(msg) == false) {
returnVal = false;
}
};
return returnVal;
});
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment