How to Delay a JavaScript HREF on Page Load?

Estimated read time 2 min read

To delay the execution of a JavaScript HREF link on page load, you can use the setTimeout() method to set a delay before the link is followed. Here’s an example of how you could delay a link with an HREF of “#example” by 3 seconds:

<a href="#example" id="delayed-link">Delayed Link</a>

window.onload = function() {
  var link = document.getElementById('delayed-link');
  link.onclick = function(e) {
    setTimeout(function() {
      window.location = link.href;
    }, 3000);

In this example, the window.onload event listener is used to ensure that the JavaScript code only runs after the page has fully loaded. The link.onclick event listener is then used to intercept the click event when the user clicks on the link. The e.preventDefault() method is called to prevent the link from being immediately followed.

Instead, the setTimeout() method is used to delay the execution of the link by 3 seconds (3000 milliseconds). After the delay, the window.location property is set to the link’s href attribute, causing the browser to follow the link.

Note that in this example, the link has an ID of “delayed-link”, which is used to identify it in the JavaScript code. You can modify this code to work with any link on your page by adjusting the ID and the href value accordingly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply