Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to make links open in new tab HTML

Understanding the Basics

When we're browsing the internet, we often click on links that take us to new web pages. In HTML, these links are created using the <a> tag. The destination web page is specified in the href attribute, like so:

<a href="">Click me!</a>

But what if we want the link to open in a new browser tab? This is where the target attribute comes into play.

The Magic of the Target Attribute

The target attribute specifies where to open the linked document. If you want the link to open in a new browser tab, you'll use the _blank value for the target attribute. Here's how it looks:

<a href="" target="_blank">Click me!</a>

When you click on this link, it will open the webpage in a new tab, keeping the current page open. This behavior is similar to keeping a book open while you look up a term in the glossary, instead of having to flip back and forth between the pages.

The Importance of Rel Attribute

While the target="_blank" attribute is a great feature, it also has a security and performance issue known as "reverse tabnabbing". Essentially, the new page can access your page and redirect it to a different, potentially malicious site when you're not looking. It's like leaving your house door open while you're away; you never know who might come in.

Thankfully, there's a simple solution to prevent this: adding rel="noopener" attribute to your link:

<a href="" target="_blank" rel="noopener">Click me!</a>

The rel attribute specifies the relationship between the current document and the linked document. When we use rel="noopener", we're telling the browser to open the link in a new process. This ensures the new page cannot access your page, protecting your users from potential threats.

Including Noreferrer in Rel Attribute

In some cases, you might also want to add noreferrer to the rel attribute. This will prevent the new page from being able to access the document.referrer property, which would reveal the URL of the page that linked to it. It's like not leaving any footprints while you're walking in the forest, so no one can trace back to you.

Here is how you can include noreferrer along with noopener:

<a href="" target="_blank" rel="noopener noreferrer">Click me!</a>

Recap and Conclusion

Creating links that open in new tabs is a useful feature for keeping users on your webpage while also directing them to other sites. This is done using the target="_blank" attribute in your link. However, it's important to also include the rel="noopener" or rel="noopener noreferrer" attributes to prevent potential security and performance issues.

In the end, remember that while using target="_blank" can improve usability by keeping your website open, it should be used wisely. Opening too many new tabs can be annoying and could lead to a poor user experience. As with many things in web development, the key is balance. Happy coding!