Wed
Wed

Reputation: 342

How to achieve internal website link click to execture something then to go to clicked link using JavaScript or jQuery

I want to achieve the following:

user clicks on the inbound website link and javascript/jquery executes something first, and when execution is over then loads next page.

I tried several techniques I found around but nothing really works for me (or I did something wrong).

Specifically, I want to run JS animation before moving to next page.

Upvotes: 0

Views: 102

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28414

Here are the steps to do this:

  1. Set a click listener to the link
  2. Use e.preventDefault() to prevent direct redirection
  3. Run the animation, I assume it will take some time, so use await to continue when it finishes
  4. redirect the page to the href attribute of the clicked link

redirectLink.addEventListener("click", redirect);
async function redirect(e){
     e.preventDefault();
     await runAnimation();
     console.log("redirecting...");
     window.location = e.target.href;
}
function runAnimation(){
     return new Promise((resolve, reject) => {
          console.log("running animation...");
          resolve();
     });
}
<a href="https://www.google.com/" id="redirectLink">Redirect</a>

Upvotes: 2

Related Questions