Solution 1 :

Don’t use onclick. Instead, add a click event listener on all anchor tags that prevents the default action (via e.preventDefault()) and instead calls the go function.

function go(page) {
  alert("You are being redirected!")
  // Important things here, such as saving
  open(page, target = "_self")
}

document.querySelectorAll('a').forEach((f) => {
  f.addEventListener('click', function(e) {
    e.preventDefault();
    go(this.getAttribute('href'));
  })
})
a {
  color: blue;
  text-decoration: underline;
  cursor: pointer;
}
Link: <a href="https://stacksnippets.net">Click me to go to the next page!</a>

Solution 2 :

Sorry about the HTML, I had to try different editors to check results.

Try this

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
  <script>

      function go(page) {
      alert("You are being redirected!")
        // Important things here, such as saving
       return false;  // equivalent to preventDefault
      }

  </script>
<body>
   <a href='http://www.example.com' onclick='return go()'>Click me to go to the next page!</a>
</body>
</html>

Or

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
  <script>

   function go(event) {
     if( !confirm(`Redirect to ${event.target.href} ?`) ) 
         event.preventDefault();
      }

  </script>
<body>
   <a href='/example' onclick="go(event)"> Click me to go to the next page! </a>
</body>
</html>

Problem :

I have an <a> inside my html page. I wrote a custom redirector in JavaScript, so that when you click the button, it runs a javascript function that performs important tasks before redirecting you. For example:

function go(page) {
  alert("You are being redirected!")
  // Important things here, such as saving
  open(page, target="_self")
}
a {
  color: blue;
  text-decoration: underline;
  cursor: pointer;
}
Link: <a onclick="go('/nextPage')">Click me to go to the next page!</a>

In the above example, the link runs the script to execute the functions then opens the URL. However, if you right click the link, there is no ‘open in new tab’ option like other links, because it doesn’t have a href. If there is a href, it goes to the next tab without running the js. Is it possible to make it so it has a href so the right-click works, but still run the JS? So basically, it would give authority to the onclick event, not running the href unless a right-click happens.

I tried removing the onclick and using href="javascript:go('/nextPage);" instead, but right clicking causes it to go to about:blank#blocked in chrome.

Comments

Comment posted by dee

yes, you’re right. edited that. Glad the solution worked for you 🙂

By