Link Targets
HTML offers you the ability to direct a user to different parts of your webpage or to a completely different webpage altogether. This is done by creating links using the anchor element <a>
. In this tutorial, we'll learn how to use the target
attribute in the anchor element to control where the linked document opens.
The Anchor Tag & href Attribute
Before we get to the target
attribute, let's have a quick recap on the anchor tag and the href
attribute. The anchor tag <a>
is used to create a link. The href
attribute is then used to specify the destination of the link.
<a href="https://www.example.com">Visit Example.com</a>
In the above example, "Visit Example.com" is what the user will see on your webpage. When they click on it, they will be taken to "https://www.example.com".
The Target Attribute
Now let's introduce the target
attribute. This attribute specifies where to open the linked document. There are four possible values for the target
attribute:
_blank
- Opens the linked document in a new window or tab_self
- Opens the linked document in the same window/tab as it was clicked (this is the default)_parent
- Opens the linked document in the parent frame_top
- Opens the linked document in the full body of the window
Let's see some examples:
- _blank
<a href="https://www.example.com" target="_blank">Visit Example.com</a>
When the user clicks on this link, it will open "https://www.example.com" in a new browser tab or window.
- _self
<a href="https://www.example.com" target="_self">Visit Example.com</a>
When the user clicks on this link, it will open "https://www.example.com" in the same tab or window where the link was clicked. This is the default behavior if no target
attribute is specified.
- _parent
<a href="https://www.example.com" target="_parent">Visit Example.com</a>
This is used in the context of frames. When the user clicks on this link, it will open "https://www.example.com" in the parent frame.
- _top
<a href="https://www.example.com" target="_top">Visit Example.com</a>
This is also used in the context of frames. When the user clicks on this link, it will open "https://www.example.com" in the full body of the window.
Conclusion
Using the target
attribute in the anchor tag, you can control how the browser behaves when a user clicks on a link. This can greatly improve the user experience on your webpage. Always think about the most intuitive way for your users to navigate your site and set your target attributes to match that.
Keep practicing and experimenting with different target
values to understand how they work. Happy coding!