Make sure jQuery on click runs before a href firing

Is it possible to make sure jQuery on click event executes before the user is forwarded to the external URL? I have been googling now for 2 hours and read a couple of posts here on stackoverflow. I just cant get this to work.

This is what I’ve tried:

HTML:

<a href="http://www.example.com/" class="external-url">Click me</a>

JS:

$('.external-url').on("click", function (e) {
  e.preventDefault();

    if (myCustomEvent()) {
      window.location = this.href;
    }
});

function myCustomEvent()
{
    setTimeout(function() {
        console.log('Execute some custom JS here before a href firing...');
        return true;
    }, 3000);
}

But it seems like the line “if (myCustomEvent()) {” is exectuted before myCustomEvent function is able to return true. Is there a better way to do this? And a way that actually works?

Answer

The jQuery click event does run before the location changes–but you’re doing something async in the middle of the click handler.

The easiest thing to do would be to pass in what you want to have happen into myCustomEvent, roughly:

$('.external-url').on('click', function (e) {
  const url = this.href
  
  e.preventDefault()
  
  myCustomEvent(function() {
    window.location = url
  });
});

function myCustomEvent(fn) {
  setTimeout(function() {
    console.log('Execute custom JS before firing navigation...');
    fn();
  }, 3000);
}

There are other ways to handle this depending on your actual requirements.