How to redirect to a new tab with HTML/JavaScript
There are multiple ways to redirect to a new tab in HTML and JavaScript. The common methods are:
Using the
window.open()function with a button in JavaScript.Using the
targetattribute with an Anchor tag.
Code example 1
Here’s an example of using a JavaScript function, window.open(). The code below is a basic HTML file with a head, title, and body. The code’s objective is to generate a web page with a button that, when clicked, opens a new tab using JavaScript, and takes the user to the provided URL.
Explanation
Let’s see the above code in detail:
Lines 2–4: We add a
headtag in which we add a title to the current tab using thetitletag.Line 6: There’s a button with the
redirectBtnID inside the body. The JavaScript file contains code that adds a click event listener to the button with the redirectBtn ID. When the button is clicked, the anonymous function inside the event listener is executed. This function declares a constant variable URL and assigns the valuehttps://www.educative.io. Then, thewindow.open()method is called with the URL variable and the target,_blank, which opens the specified URL in a new tab.
Code example 2
Now, let’s see an example of redirecting to a new tab using a link in HTML. The code below is a basic HTML file with a head, title, and body. The code’s objective is to generate a web page with a hyperlink that, when clicked, opens a new tab and takes the user to the provided URL.
Explanation
Let’s see the above code in detail:
Lines 2–4: We add a
headtag in which we add the title to the current tab using thetitletag.Line 6: There's an anchor element,
<a>, inside the body with anhrefattribute set tohttps://www.educative.io. The text within the anchor element is"Redirect to a New Tab". Thetarget="_blank"attribute in the anchor element ensures that when the link is clicked, the URL will open in a new tab instead of navigating away from the current page.
Free Resources