Skip to content
the poor coder

load url onclick javascript

Poor Man
Published
Reading time
2 min read
On this page

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:

Text

<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:

Text

<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:

Text

<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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC