Wednesday 21 August 2013

How to open and close pop up window in asp.net using javascript

                              How to open and close pop up window in asp.net using java script


Sometimes it is required to open the page of your website or any other website in popup window on click of link or button or any other. This articles will show how to open page of your website or any other website in popup window that appear on center of the parent window on click of link using JavaScript.
  •  Copy and Paste the following JavaScript function in the head tag of your page as:
<head runat="server"
<script language="javascript" type="text/javascript">
        var win = null;
        function OpenPopUp(mypage, myname, w, h, scroll, pos) {
            if (pos == "random") { LeftPosition = (screen.width) ? Math.floor(Math.random() * (screen.width - w)) : 100; TopPosition = (screen.height) ? Math.floor(Math.random() * ((screen.height - h) - 75)) : 100; }
            if (pos == "center") { LeftPosition = (screen.width) ? (screen.width - w) / 2 : 100; TopPosition = (screen.height) ? (screen.height - h) / 2 : 100; }
            else if ((pos != "center" && pos != "random") || pos == null) { LeftPosition = 0; TopPosition = 20 }
            settings = 'width=' + w + ',height=' + h + ',top=' + TopPosition + ',left=' + LeftPosition +',scrollbars=' + scroll +',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=yes';
            win = window.open(mypage, myname, settings);
        }
</script>
</head>

  • Now paste the following in the body tag of the page where you want the link to appear
<a href="http://www.webcodeexpert.com" onclick="OpenPopUp(this.href,'mywin','1050','555','yes','center');return false"onfocus="this.blur()">Click here to open pop up window</a>

This example will open http://www.webcodeexpert.com  in pop up window but if you want
to open another page of your website just replace the http://www.webcodeexpert.com with you page name e.g.
<a href="default2.aspx" onclick="OpenPopUp(this.href,'mywin','1050','555','yes','center');return false"onfocus="this.blur()">Click here to open pop up window</a>

Now it will open default2.aspx page in pop up window.

How to close pop up window?

Now one question arise how to close the pop up window instead of the close button? To do this just  write as :
<asp:LinkButton id="lkCloseWindow" runat="server" Text="Close window"OnClientClick="window.close();"></asp:LinkButton>
On the page that opens in pop up window. It will create a link to close the window.

No comments:

Post a Comment