load url onclick javascript

Load URL OnClick JavaScript

Have you ever wanted to redirect your website's visitors to another page by clicking a button or a link? If so, you can do this easily by using JavaScript. Using the onClick event, you can load a URL when a user clicks on an object, such as a button or a link.

Method 1: Using a Button

The first method is to use a button to trigger the URL load. Here's an example:


<button onclick="window.location.href='http://example.com'">
   Click here to go to Example.com
</button>

In this code, we define a button element that has an onClick event. When the button is clicked, it will trigger the window.location.href property, which will redirect the user to the specified URL.

The second method is to use a link element to trigger the URL load. Here's an example:


<a href="#" onclick="window.location.href='http://example.com'">
   Click here to go to Example.com
</a>

In this code, we define a link element that has an onClick event. When the link is clicked, it will prevent the default action (which is to follow the link), and then trigger the window.location.href property, which will redirect the user to the specified URL.

Method 3: Using a Function

The third method is to use a JavaScript function to trigger the URL load. Here's an example:


<button onclick="loadUrl()">
   Click here to go to Example.com
</button>

<script>
function loadUrl() {
   window.location.href = "http://example.com";
}
</script>

In this code, we define a button element that has an onClick event that calls the loadUrl() function. When the button is clicked, it will trigger the loadUrl() function, which will redirect the user to the specified URL by setting the window.location.href property.

These are three different methods that you can use to load a URL when a user clicks on an object using JavaScript. Choose the method that best suits your needs and implement it in your website.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe