There are several ways to open a link in a new tab using JavaScript. Here are eight effective ways:
- Using target attribute: The easiest way to open a link in a new tab is to add the target attribute to the link and set its value to “_blank”. For example:
<a href="https://www.example.com" target="_blank">Link</a>
Using window.open(): You can use the window.open() method to open a link in a new tab. For example:
window.open("https://www.example.com", "_blank");
Using location.href: You can also use the location.href property to redirect the current page to the link in a new tab. For example:
window.location.href = "https://www.example.com";
Using a function: You can define a function to open a link in a new tab and call it when needed. For example:
function openInNewTab(url) {
var win = window.open(url, '_blank');
win.focus();
}
openInNewTab("https://www.example.com");
Using a link element: You can create a link element dynamically and add it to the DOM to open a link in a new tab. For example:
var link = document.createElement("a");
link.href = "https://www.example.com";
link.target = "_blank";
document.body.appendChild(link);
link.click();
Using a form: You can also use a form with a target attribute set to “_blank” to open a link in a new tab. For example:
<form action="https://www.example.com" method="get" target="_blank">
<input type="submit" value="Link">
</form>
Using a button element: You can create a button element and add an event listener to it to open a link in a new tab. For example:
var button = document.createElement("button");
button.textContent = "Link";
button.addEventListener("click", function() {
window.open("https://www.example.com", "_blank");
});
document.body.appendChild(button);
Using the anchor element’s click method: You can also simulate a click on the link element to open a link in a new tab. For example:
var link = document.createElement("a");
link.href = "https://www.example.com";
link.target = "_blank";
document.body.appendChild(link);
link.click();
These are some of the most effective ways to open a link in a new tab using JavaScript.