There may be multiple reasons why users want to click a link. Following are some scenarios where we require to click a link programmatically.
The logic behind this functionality is that we will get the element using any of the DOM selector methods and apply the click() function to it.
Consider the below example:
The Script will be as follows to trigger the click functionality:
Let's understand its different scenarios:
On Page Load Redirect After Delay
We may require to redirect a user to another page when a page is loading. In such case, the above approach will be helpful. Here, we will redirect a user to another page at the page load time. A countdown will begin at page load. When the countdown is completed, a link will be clicked.
Below is the implementation of this:
In the below example, we are taking the countdown timer for 1s.
Let's consider the below HTML code:
The complete code of the above example is:
In the above example, when the page is loaded, the immediate Script is called having the setTimeout function, which will execute the function redirect after one second. It will redirect the user to another page.
When the redirectTo function is launched, it will target the anchor tag by its id and apply a click() function.
Let's consider an other example where we need to show some message to the users on a specific user action and redirect them to another page.
For example, if a user booked any product when it is successfully booked, we need to redirect him to another page. There may be many scenarios for which we need to implement this functionality. Let's understand it with a simple example.
For example, we have a div, and we want to display a message to the user and then redirect him to another page.
We will be performing it in the following three parts:
Below is the code for the link:
From the above code, we are getting the DOM element using id value . There is no text in the above tag, so that it will be invisible to DOM. So, for that, we need to add the div element to DOM.
In the below code, we have a div where we will get the user action and allow him to trigger some function by clicking.
Collectively, we can use the below code:
The above example will display an alert message "You have clicked on div". Once we click on the OK button, it will redirect the user to the specified link. Though alert() is optional, you can use any other way to display the message, like in a modal box or a toaster and so on.
We have discussed a few use cases in this example. They can be helpful in providing the idea and logic for similar examples.
It was a simple logic having a link with the id attribute and without the text so that it would not be visible to the DOM, and getting the value from its id and applying the click() function on it. We can have many other methods to perform the same action, like we can use any other DOM method or can choose the event listeners to trigger the event. But, using id, it was an easy way to perform the task.