jQuery Open Link in New Tab

Opening links in new tabs is a fundamental web development skill that enhances user experience by keeping visitors on your site while providing access to external resources.

In this comprehensive tutorial, we’ll explore multiple jQuery methods to open links in new tabs, covering everything from basic implementations to advanced techniques.

Open Links in New Tabs

Before diving into the code, it’s important to understand when and why you should open links in new tabs:

  • Retain users: Keep visitors on your main website
  • External links: Direct users to external resources without losing them
  • Better UX: Allow users to reference multiple pages simultaneously
  • E-commerce: Open product details while maintaining shopping flow

Method 1: Use jQuery with window.open()

The most reliable and widely supported method uses jQuery’s click() event handler combined with JavaScript’s window.open() function.

Basic Implementation

$(document).ready(function() {
    $('.open-new-tab').click(function(e) {
        e.preventDefault();
        var url = $(this).attr('href');
        window.open(url, '_blank');
    });
});

HTML Structure

This section defines simple anchor tags that link to external websites, each designed to open in a new browser tab.

<a href="https://www.example.com" class="open-new-tab">Visit Example.com</a>
<a href="https://www.google.com" class="open-new-tab">Open Google</a>

Enhanced Version with Error Handling

This script uses jQuery to safely open links in new tabs while detecting and alerting users if pop-ups are blocked.

$(document).ready(function() {
    $('.external-link').click(function(e) {
        e.preventDefault();
        var url = $(this).attr('href');

        if (url && url.length > 0) {
            var newWindow = window.open(url, '_blank', 'noopener,noreferrer');

            // Check if popup was blocked
            if (!newWindow || newWindow.closed || typeof newWindow.closed == 'undefined') {
                alert('Please allow popups for this website');
            }
        }
    });
});

I executed the above example code and added the screenshot below.

Open Link in New Tab jQuery

Method 2: Dynamic Target Attribute Modification

This approach dynamically adds the target=”_blank” attribute to links, which is cleaner and requires less JavaScript.

$(document).ready(function() {
    // Open all external links in new tabs
    $('a[href^="http"]').not('[href*="' + location.hostname + '"]').attr('target', '_blank');

    // Or target specific classes
    $('.new-tab-link').attr('target', '_blank').attr('rel', 'noopener noreferrer');
});

I executed the above example code and added the screenshot below.

jQuery Open Link in New Tab

HTML Example

This snippet creates clickable links that open Stack Overflow and GitHub in new browser tabs using the new-tab-link class for easy jQuery targeting.

<a href="https://www.stackoverflow.com" class="new-tab-link">Stack Overflow</a>
<a href="https://www.github.com" class="new-tab-link">GitHub</a>

Method 3: Button Click to Open Links

Sometimes you need to open links through button clicks rather than direct anchor tags. This is common in web applications and forms.

$(document).ready(function() {
    $('#openLinkBtn').click(function() {
        var targetUrl = $(this).data('url');
        window.open(targetUrl, '_blank', 'width=800,height=600,scrollbars=yes,resizable=yes');
    });

    // Multiple buttons with different URLs
    $('.action-button').click(function() {
        var url = $(this).data('target-url');
        var windowName = $(this).data('window-name') || '_blank';
        window.open(url, windowName);
    });
});

HTML Structure

This example defines buttons that open external sites, one for jQuery documentation

<button id="openLinkBtn" data-url="https://www.jquery.com">Open jQuery Docs</button>
<button class="action-button" data-target-url="https://www.w3schools.com" data-window-name="w3schools">W3Schools</button>

I executed the above example code and added the screenshot below.

Open Link in New Tab in jQuery

Method 4: Advanced External Link Detection

This sophisticated approach automatically detects and handles external links:

$(document).ready(function() {
    function openExternalLinks() {
        $('a').each(function() {
            var link = $(this);
            var href = link.attr('href');

            // Check if it's an external link
            if (href && (href.startsWith('http://') || href.startsWith('https://')) 
                && !href.includes(window.location.hostname)) {

                link.attr('target', '_blank');
                link.attr('rel', 'noopener noreferrer');

                // Add visual indicator
                link.addClass('external-link');
            }
        });
    }

    // Run on page load
    openExternalLinks();

    // Run again if content is dynamically added
    $(document).on('DOMNodeInserted', function() {
        openExternalLinks();
    });
});

CSS for Visual Indicators

This style adds a small arrow icon next to external links and underlines them on hover, helping users recognize links that open in new tabs.

.external-link::after {
    content: " ↗";
    font-size: 0.8em;
    color: #007cba;
}

.external-link:hover {
    text-decoration: underline;
}

Method 5: Form Integration

Opening links in new tabs from form submissions or form elements:

$(document).ready(function() {
    $('#searchForm').submit(function(e) {
        e.preventDefault();
        var query = $('#searchInput').val();
        var searchUrl = 'https://www.google.com/search?q=' + encodeURIComponent(query);
        window.open(searchUrl, '_blank');
    });

    // Dropdown selection
    $('#quickLinks').change(function() {
        var selectedUrl = $(this).val();
        if (selectedUrl) {
            window.open(selectedUrl, '_blank');
            $(this).val(''); // Reset dropdown
        }
    });
});

HTML Form Example

This form lets users search or quickly open selected links in a new tab, offering both input-based and dropdown-based navigation options.

<form id="searchForm">
    <input type="text" id="searchInput" placeholder="Enter search term">
    <button type="submit">Search in New Tab</button>
</form>

<select id="quickLinks">
    <option value="">Quick Links</option>
    <option value="https://www.github.com">GitHub</option>
    <option value="https://www.stackoverflow.com">Stack Overflow</option>
</select>

Security Best Practices

When opening links in new tabs, always include security attributes:

1. Use rel=”noopener noreferrer”

Prevents the newly opened tab from accessing your page’s window object, enhancing security.

$('.secure-link').attr('rel', 'noopener noreferrer');

2. Validate URLs

Ensures that only safe and properly formatted links are opened, protecting users from malicious redirects.

function isValidUrl(url) {
    try {
        new URL(url);
        return url.startsWith('http://') || url.startsWith('https://');
    } catch {
        return false;
    }
}

$('.validated-link').click(function(e) {
    e.preventDefault();
    var url = $(this).attr('href');

    if (isValidUrl(url)) {
        window.open(url, '_blank', 'noopener,noreferrer');
    } else {
        alert('Invalid URL');
    }
});

Browser Compatibility and Fallbacks

Ensure your implementation works across different browsers:

$(document).ready(function() {
    $('.compatible-link').click(function(e) {
        e.preventDefault();
        var url = $(this).attr('href');

        // Modern browsers
        if (window.open) {
            window.open(url, '_blank', 'noopener,noreferrer');
        } 
        // Fallback for older browsers
        else {
            $(this).attr('target', '_blank');
            window.location.href = url;
        }
    });
});

Performance Optimization Tips

  1. Use event delegation for dynamically added content:
$(document).on('click', '.dynamic-link', function(e) {
    // Handler code here
});
  1. Cache jQuery objects:
var $links = $('.tab-links');
$links.attr('target', '_blank');
  1. Minimize DOM queries:
$(document).ready(function() {
    var $body = $('body');
    $body.on('click', '.new-tab', function(e) {
        // Event handling
    });
});

Opening links in new tabs with jQuery is a versatile skill that enhances user experience when implemented correctly. Whether you’re using window.open(), modifying target attributes, or handling form submissions, always prioritize security, accessibility, and performance. Remember to test across different browsers and devices to ensure consistent behavior.

The methods covered in this tutorial provide a solid foundation for handling new tab functionality in your web applications. Choose the approach that best fits your specific use case and always consider the user experience implications of opening content in new tabs.

You may also like to read:

Leave a Comment

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.