I currently have a webpage in a format similar to this, with a sidebar and iframes with sources pointing to other pages on my website.

I have the following code to offer user a confirm box for if they wish to leave the page:
window.onbeforeunload = function(e) {
return 'All unsaved data will be lost.';
};
In the iframes, I have various HTML elements, such as textfields, input boxes, buttons, etc. I don’t want the user to get the onbeforeunload function unless they have clicked on one of these input elements first.
Of course, I could go in and code each textfield, button, etc, manually using by creating a variable such as shouldPopup, then using onclick to set shouldPopup to TRUE, and finally using an onbeforeunload if statement, but this is inconvenient and, if I were to perhaps make more changes in the future, I would potentially have to go in and modify each element one by one again.
What is a better way to get the same results? Any input as to how to simplify the code is greatly appreciated! 🙂
Update:
Some more information about my Iframes. I am using the jQuery library for some basic functions (nothing fancy). There’s quite a bit of PHP in them, as well as a few database requests, but nothing out of the ordinary. Hopefully this information is helpful to anyone looking to make any suggestions
If you don’t want to change too much of your code, I think toggeling a flag is OK. The following is a simple, pragmatic approach.
Example form:
Monitor changes in both iFrames:
Parent page:
This code is braindump, it’s untested.
Note: If your pages are served from different domains than the parent page you’ll run into cross site scripting issues. In that case you’re not able to access the parent page’s Javascript. Then you have to use postMessage() to send messages to your parent page’s domain.
I’d suggest you to take a look at Backbone.js:
Edit 1:
Backbone can help you managing the state of your form. In Backbone a Model will represent your form data. A View – representing your form (form’s inputs) – is bound to that Model. It will monitor your form fields and set() attributes on the model. A Backbone Model has its own state, you can check if the form has chnaged using e.g. the changed() method. Separating Model and View in your application is always a good idea, it helps separating the responsibilities.
I just wanted to give you another idea.
Edit 2:
Fixed the code that triggers an event in the top window. I was not sure if
$(window.top)works. It does not work. I’m not sure why. I’ve tested it and this code is correct:I’ve updated the above code.