This blog will guide you about going to URL onclick in JavaScript.
Go to URL using “onclick” Event in JavaScript
To go to URL using onclick event in JavaScript, you can use:
- The “window.open()” method.
- The “window.location” object method.
We will now go through each of the mentioned methods one by one!
Method 1: Go to URL With onclick in JavaScript Using window.open() Method
In JavaScript, the “window.open()” method is used for opening a new browser window. You can also utilize this method to go to a specified URL using the button “onclick” event.
Syntax
Here, “url” refers to the website link, “windowName” is the name of the window, and “specs” refers to the comma-separated list of items.
Look at the below-given example.
Example
In the example below, we will add a button and specify its “onclick” event in such a way that when the button is clicked, the onclick event will access the function “openGoogleByMethod()”:
<button type= "button" id= "btn" onclick= "openGoogleByMethod()">Open Google</button>
</body>
Now, we will define a function “openGoogleByMethod()” and use the “window.open()” method and pass the “URL” of the “Google” site in it as an argument. This will result in opening the specified site in a new tab:
function openGoogleByMethod(){
window.open("https://www.google.com")
}
</script>
The output of the above implementation will result in:
Method 2: Go to URL With onclick in JavaScript Using window.location() Method
The “window.location()” method can be used to fetch the current page (“URL”) and then redirect the browser to a new page address. You can also utilize this method to access the specified URL using the “location” object.
Let’s go through the following example for better understanding:
Example
In our JavaScript, we will apply the “window.location()” method, where the “location” object will contain the information on the current location, which is “Google” in this case. The “window.location.href” property will then return the URL of the page specified in the window.location:
function openGoogleByMethod(){
window.location("https://www.google.com");
window.location.href = "https://www.google.com";
}
</script>
Execution of the above-given code will result in the following output:
We have provided all the simplest methods to go to the URL by applying onclick in JavaScript.
Conclusion
In JavaScript, to go to URL with onclick, you can use the “window.open()” method to open the window with the specified “URL” or apply the “window.location” object method to specify the location of the specified URL and the “window.location.href” property to return the URL of the specified page.
This article has explained the methods to go to the URL using onclick in JavaScript.