Monday, November 7, 2011

0

jQuery Solution to Open external links in a new window in blogger

  • Monday, November 7, 2011
  • Share
  • We sometimes put links in our posts. And naturally our visitor will click on those links. By default when a link is clicked it will open in the same window.

    If your blog is like mine where visitors only come in once in a blue moon ha-ha, keeping them in your blog once they come in is crucial. We wouldn't want them visitors disappear from our blog through outbound links, now would we?

    But don’t worry guys, we can prevent or at least delay this by opening the links in a separate window or tab. This can be achieved by adding a small Java Script in your blogger template.



    You have to add it to your Layout => Edit HTML (Do Not Check Expand Button) => Find </body>=> Add the Code before </body>

    This code actually should work on any site not just blogger.

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript">
    </script>
    <script type="text/javascript">
    //<![CDATA[
    jQuery('a').each(function() {
        // Let's make external links open in a new window.
        var href = jQuery(this).attr('href');
        
        if (typeof href != 'undefined' && href != "" && (href.indexOf('http://') != -1 || href.indexOf('https://') != -1) && href.indexOf(window.location.hostname) == -1) {
            jQuery(this).attr("target", "_blank");
        }
    });
    //]]>
    </script>


    FAQ


    Q: Which does the code open ?
    A: The code opens external links such as links starting with http:// and https:// in a new (_blank) window.


    Q: Does this code open adsense links in a new window?
    A: No. Adsense links won't be opened in a new window because the they are loaded in an IFRAME which lives in its own world and its contents can't be manipulated.

    By the way my blog is using this trick only.

    Good luck!

    0 Responses to “jQuery Solution to Open external links in a new window in blogger”

    Post a Comment

    Related Posts Plugin for WordPress, Blogger...