jijo thomas
jijo thomas

Reputation: 337

how to close a popup window when the focus is gone out from it

Requirement: A popup will be opened up from parent window, and it should get closed when the focus from the window is lost. (This should happen even when another application window is opened or came into focus).

Tried code: <body onBlur='javascript:window.close();'>

Issue: On click within the body of the popup makes the popup closed.

Compatibility: ie6 and above, firefox.

I got a workaround from http://pro-thoughts.blogspot.com/2006/10/incorrect-behavior-of-windowonblur.html

var active_element;  
var bIsMSIE;

function initiateSelfClosing() {  
  if (navigator.appName == "Microsoft Internet Explorer") {  
    active_element = document.activeElement;  
    document.onfocusout = closeWnd;  
    bIsMSIE = true;  
  }  
  else { window.onblur = closeWnd; }  
}

function closeWnd() {  
  if (window.opener != null) {  
    if (bIsMSIE && (active_element != document.activeElement)) {  
      active_element = document.activeElement;  
    }  
    else {  
      window.close();  
    }  
  }  
}  


<body onload="initiateSelfClosing()">  
</body>

But here also one problem is there, if there is a print button in the page, and if am clicking on print > then cancelling the print job, the popup is getting closed.

Can some one help me pls...

Upvotes: 5

Views: 16062

Answers (3)

Sami
Sami

Reputation: 8419

Little corrections in sathishkumar's answer

1.we need to convert win to jquery object

2.Apply blur event on jqvariable and not on window

3.this.close is good enough in definition of onblur event

 var win = window.open("URL");
 var jqwin = $(win);
  $(jqwin).blur(function() {
    this.close();
 });

Upvotes: 2

Pranav
Pranav

Reputation: 8871

You cannot attach onblur event to BODY but
you Can attach a function on Onblur event of window.

<script type="text/javascript">
    function closeme()
    {  
        window.close();
    }
    window.onblur=closeme;
</script>

Since you have Edited your Question, You can get more help here

Upvotes: 1

sathishkumar
sathishkumar

Reputation: 1816

Use document for blur event

  var win = window.open("URL");
  $(window).blur(function() {
    win.close();
  });

Upvotes: 1

Related Questions