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 Solid
- Getting Started with Svelte
- Getting Started with Express
- Create an RSS Reader in Node
- Getting Started with Electron
- How to deploy a .NET app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Vuex: Managing State in Vue