JavaScript program to open one url in a new tab

Open one URL in a new tab :

The anchor tag is used in HTML to open one new link in a new page. You can use this tag if you have a static URL. But, sometimes, we may need to do it dynamically as if the user clicks on a button, we will open one link in a new tab. We need JavaScript for that. JavaScript provides one method called window.open() that can be used to open a link in a new browser tab.

In this post, I will show you how to open one URL in a new tab using JavaScript.

How to open a URL in a new tab in ‘a’ attribute :

The below __ target attribute will open the URL in a new tab on click :

<a href="https://www.codevscolor.com" target="_blank">Click here</a>

Using JavaScript :

We will use window.open() to replicate the exact behavior. The first parameter should be the URL we are opening and the second parameter is _blank.

<!DOCTYPE html>
<html>
<body>

<button id="button" type="button">Click Here</button>

</body>
<script>
function openUrl(){
  window.open('https://www.codevscolor.com', '_blank');
}

document.getElementById("button").onclick = function() {openUrl()};

</script>
</html>

In this example, if you click on the button, the javascript will invoke the openUrl method that will open the URL in a new tab.

javascript open link in new tab

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊