Reputation: 405
I have a form implemented in a fancybox (version 2.1.5) iframe. People can choose to not to fill up the form and click on "X" to close fancybox form or alternately fill up the form and click on Register.
I have a beforeClose
callback setup to set cookies and do some work. But I want this to be triggered only if someone clicks on "X" or Esc key. See code below
$.fancybox.open({
type: "iframe",
href: "/[url].php",
autoSize: true,
height: "auto",
margin: 0,
padding: 0,
autoCenter: true,
maxWidth: 460,
maxHeight: 615,
modal: false,
iframe: {
scrolling: "no"
},
beforeClose: function () {
//set cookie code
},
});
But if someone was to Register, it will show a Thank you message for 2 seconds and close the fancybox. This is done by using window.parent.$.fancybox.close();
See detailed code below
$.post('/register.php', post_vars, function(data) {
window.parent.$.fancybox.close();
});
However I do not want the beforeClose
event to be called in case I close it from the iFrame or even if it gets called, I need to somehow know that it has been done from the iframe & not using the "X" button.
Is there a way to differentiate this?
Upvotes: 1
Views: 6166
Reputation: 11
This will be triggered only if someone clicks on "X" or Esc key
$(document).ready(function () {
$(".fancybox").fancybox({
closeClick: false, // prevents closing when clicking INSIDE fancybox
openEffect: 'none',
closeEffect: 'none',
enableEscapeButton: false,
helpers: {
overlay: {
closeClick: false // prevents closing when clicking OUTSIDE fancybox
}
},
beforeClose: function () {
return confirm('Are you sure?')
}
})
});
Upvotes: 1
Reputation: 41143
I can think different ways to do this, like binding custom events to the fancybox close button or catching the escape key with keyup
or keypress
, etc.
I guess the simplest way is to create in the parent page, a custom close function like :
var closedFromIframe = false;
function customClose() {
closedFromIframe = true;
jQuery.fancybox.close();
}
This function will close fancybox (from the parent page itself) when invoked from the iframed page AND will enable the (previously defined) closedFromIframe
flag, so instead of this :
$.post('/register.php', post_vars, function(data) {
window.parent.$.fancybox.close();
});
... you could do
$.post('/register.php', post_vars, function(data) {
window.parent.customClose();
});
Then, in your fancybox script you could validate within the beforeClose
callback, the status of the closedFromIframe
flag and do whatever you need to :
$.fancybox.open({
// your API options
beforeClose : function () {
if (closedFromIframe) {
// closed from iframe custom function
} else {
// close button -or- escape key
}
},
afterClose : function () {
closedFromIframe = false; // reset flag
}
});
Notice we are also resetting the closedFromIframe
flag within the afterClose
callback.
See a DEMO of this implementation.
Upvotes: 2