Table of Contents
Links on the web, also known as hyperlinks, are used to link to other web pages. By default, links open in the same tab that you're currently on.
This is a sensible default as it means you can keep browsing the web all in the same tab.
However, sometimes, you don't want your users to navigate away from the page you're on.
In these situations, you'll want to open the link in a new tab and override the default behavior.
In this post, we'll learn how to open links in a new tab in HTML.
Using the target attribute
To open a link in a new tab, you'll need to add the target attribute to the link.
First, let's start off with a basic link:
HTML<a href="https://sabe.io">
Sabe.io
</a>
Now, let's add the target attribute to the link. To make the link open in a new tab, give the attribute a value of _blank:
HTML<a href="https://sabe.io" target="_blank">
Sabe.io
</a>
If you want to increase security, you can also add the rel attribute to the link, like this:
HTML<a href="https://sabe.io" target="_blank" rel="noopener noreferrer">
Sabe.io
</a>
Using JavaScript
This method is not recommended as it requires JavaScript, but if you want to do this programmatically, you can use the window.open method and bind it to the click event.
That way, when the link is clicked, the window.open method will open the link in a new tab.
Let's see an example:
HTML<a onclick="window.open('https://sabe.io')">
Sabe.io
</a>
Conclusion
In this post, we've seen how to open links in a new tab in HTML. We've also seen how to open links in a new tab using JavaScript and binding to the click event.
Hopefully, this post has been useful to you.
Thanks for reading!
How to Install Node on Windows, macOS and Linux
Getting Started with Solid
Managing PHP Dependencies with Composer
Getting Started with Electron
How to Set Up Cron Jobs in Linux
Best Visual Studio Code Extensions for 2022
How to deploy a Deno app using Docker
Using Puppeteer and Jest for End-to-End Testing
Getting Started with React
Getting Started with Vuex: Managing State in Vue
Setting Up a Local Web Server using Node.js
Getting Started with Moon.js
