In this Answer, we'll learn how to use HTML and JavaScript to open a link in a new tab.
HTML (HyperText Markup Language) is a markup language that determines the content and structure of a web page.
To open a link in HTML in a new tab, we use the target
attribute in the opening <a>
tag. The value of this attribute should be set to _blank
. When the link text is clicked, the website link opens in a new tab.
In line 7:
The <a>
element in HTML is used to integrate URLs in websites.
The href
attribute sets the link address that the user will be directed to when they click on the link text.
The URL https://www.educative.io/
is the value of the
href
attribute.
The target
attribute determines where the link would be opened.
The value of the target
attribute _blank
opens the link in a new tab.
The text Educative
is the link text between the opening <a>
tag and closing </a>
tag.
JavaScript is a programming language used to make websites more responsive, interactive, and user-friendly. It can access and modify an HTML web page's content, define the set of instructions that the web page should follow, and react to events triggered by the browser or user.
To open a URL in a new tab/window in JavaScript, we use the window.open
(URL, target)
method. To open a new tab, however, we must use _blank
as the second parameter of this method.
Note: Avoid adding a third parameter because the link will be redirected to a new window rather than a new tab.
Line 7: We use the event attribute onclick
to call the function openTab()
which executes the script when the button is pressed.
Line 9: We use the <script>
tag to specify a scripting language in the HTML document.
Lines 10–12: The function openTab()
is used to contain the lines of code that will be run to open a link in a new tab with JavaScript. The following is the explanation of it.
We use the window.open
()
method to open a new tab or window.
We input the link to the website https://www.educative.io/
in the first parameter of the method.
We use the target
attribute to specify where to open the link.
We use the value of the target
attribute _blank
to open the link in a new tab.