Thursday, May 10, 2012

Open link in new tab or new popup window using jQuery

Well, do you know that opening a link in new tab and open link in a new popup window are 2 different things? And to implement both the functionality, One need to use different codes. I had never given this a thought before writing this article but I realized that these are 2 different things (silly mistake). In this post, I will show you how to open a link in new tab and how to open a link a popup window using jQuery.

For example, I have placed 2 hyperlink HTML element on the page. One with ID "Popup" and other one with ID "NewTab".
//Code Starts
<a href="http://jquerybyexample.blogspot.com/" id="Popup">
    Open in Popup window </a>

<a href="http://jquerybyexample.blogspot.com/" id="NewTab" >
    Open in New Tab</a>
//Code Ends
Now, to open link in new Tab, all you need to do is to assign "target=_blank" to the Hyperlink tag.
//Code Starts
$(document).ready(function() {
   $('#NewTab').click(function() {
        $(this).target = "_blank";
        window.open($(this).prop('href'));
        return false;
   });
});​
//Code Ends
To open link in a new window, create a new object of window. And set focus on it.
//Code Starts
$(document).ready(function() {
   $('#Popup').click(function() {
     var NWin = window.open($(this).prop('href'), '', 'height=800,width=800');
     if (window.focus) 
     {
       NWin.focus();
     }
     return false;
    });
});​
//Code Ends
See result below.


See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.