How to Use jQuery to Dynamically Open Links in New Tabs

Even if you're a new or beginning developer, you probably know that you can easily make links open in new tabs by using the target attribute with your anchor tags. To make a link open in a new tab, all it takes is to make your HTML look like this:

<a href="/link/" target="_blank"></a>

The target="_blank" attribute is all you need to make your links open in new tabs. But what if your anchor tags weren't written this way, and you still want your links to open in new tabs? You can go back through your HTML and hand code it yourself, but if you've got a lot of anchor tags this could take you a really long time. Luckily, jQuery is here to save the day.

With jQuery,  you can use some really straightforward snippets to dynamically open all external links in new tabs without having to go through every line of your HTML with a fine-toothed comb. To see the snippet for yourself, check out the code below:

$('a[@rel$='external']').click(function(){
     this.target = "_blank";
});

That's it. All it takes are two lines of  jQuery to make sure that all of your external links open in new tabs. The function is triggered by the .click() event method, so the function won't run unless any of the external links are clicked on, so it's a pretty lightweight solution. You can see that the snippet above uses the 'a[@rel$='external']' selector. This can be used to select all of the external links, and apply the target="_blank" attribute to it. But, if you find yourself wanting to select all of the anchor tags on your page, you can remove the rel code and simply use 'a' as the selector. You can also use a similar concept to select all links of one class or ID type by placing the class or ID name in the selector.



Responsive Menu
Add more content here...