How to Open URL on Button Click in javascript

In this video tutorial, you will learn how to open a URL on button click in javascript.  Generally, we always use an anchor tag  for external or internal links. Anchor tag has href attribute where we specify the page we want to open when somebody clicks on that element.

As you know there is no href attribute for the button element, so javascript is our best option here.  Also, an anchor tag is a great option if the URL is not dynamic. To open dynamic URLs, we have to make use of javascript.

In javascript, the window object contains open() method and this method can be used to open any URL dynamically. I suggest you to check out MDN docs to learn more about it.

In the following example, we have an input field and a button element. We will enter some random URL in the input field and upon click of a button, we will load that URL in a new window. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, input, and button).
  • The innerText for the button element is ”Open”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div>
        <input type="text" placeholder="Enter Url">
        <button>Open</button>
    </div>
    <script src="script.js"></script>
</body>
</html>
div {
    display:flex;
    justify-content: center;
}

input, button {
    display: inline-block;
    padding: 10px;
    margin-top: 5px;
}

Javascript

  • We have selected the button element and the input element using the document.querySelector() method and stored them in btnOpen and input variables respectively.
  • We have attached the click event listener to the button element.
  • In the event handler function, we are calling the open() method of the window object and passing it 3 parameters.
  • The first parameter is the URL to which we want to navigate and we are getting this from the input element using value property.
  • The second parameter specifies the target attribute or name of the window. In our case, we want to load the URL in the new window and that is why we are passing “_blank”.
  • In the third parameter, we are passing a comma separated string to make sure the height and width of the new window should be 600px.
let btnOpen = document.querySelector('button');
let input = document.querySelector('input');

btnOpen.addEventListener('click', () => {
    window.open(input.value, '_blank', 'height=600px, width=600px');
});