April 29, 2012

Window resize issue in jQuery Popup

Question by agurchand

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!.

Answer by Mark

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);

Answer by Starx

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();
});
...

Please fill the form - I will response as fast as I can!