Reputation: 1665
I started writing a very Simple jQuery Popup myself.
Here is the code
<script type="text/javascript">
$(document).ready(function(){
$("#pop").click(function(){
openPopup();
});
$("#close").click(function(){
closePopup();
});
});
function openPopup(){
$("#overlay_form").css({
left: ($(window).width() - $('#overlay_form').width()) / 2,
top: ($(window).width() - $('#overlay_form').width()) / 7,
position:'absolute'
});
$("#overlay_form").fadeIn(1000);
}
function closePopup(){
$("#overlay_form").fadeOut(500);
}
$(window).bind('resize',openPopup);
</script>
Everything is working fine. But the problem is here in this code
$(window).bind('resize',openPopup);
This code is to keep the popup in the center of the browser. But, even after i close the popup, if i resize the browser this code again opens up the popup.
I need to use a if condition somewhere in the code!. Where to use and how to use?. Give me a solution please!.
Upvotes: 0
Views: 3894
Reputation: 11
The solution that you are looking for is really quite simple--when you find it . . .
Within your document ready function add a function that fires during a browser resize event; within that function re-center your dialog:
$(document).ready(function () {
$(window).resize(function() {
$('#overlay_form').dialog('option', 'position', 'center');
});
});
By the way, when you are opening your dialog there is no need to specify top or left, as the default position is center.
Upvotes: 1
Reputation: 40863
Remove the .fadeIn()
from the function and place it in the click handler.
$("#pop").click(function(){
$("#overlay_form").fadeIn(1000);
resizePop();
});
function resizePop(){
if(!$("#overlay_form").is(':visible')){
return;
}
$("#overlay_form").css({
left: ($(window).width() - $('#overlay_form').width()) / 2,
top: ($(window).width() - $('#overlay_form').width()) / 7,
position:'absolute'
});
}
$(window).bind('resize',resizePop);
Upvotes: 1
Reputation: 11613
if( $("#overlay_form").is(':visible') ) {
// it's showing, so recenter it
}
else {
// it's hidden, so you don't care
}
I recommend that you separate the re-centering code from the opening code so you can call them more specifically based on the circumstances.
Upvotes: 0
Reputation: 78971
First of all bind
is deprecated, use .on()
from jQuery 1.7 and next, your event handling fails when the popup boxes is faded out, so limiting the resize then event handler to one function causes the script to break.
$(window).on('resize',function() {
openPopup();
});
Upvotes: 0