How to Open Link in a New Tab in HTML
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!
- Getting Started with Svelte
- How to Serve Static Files with Nginx and Docker
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase