HTML5, CSS3, jQuery, JSON, Responsive Design...

JavaScript links and right-click annoyances!

Michael Brown   May 27 2010 06:49:44 AM
Scenario
Sometimes you want the user to be warned in some way before (s)he clicks on a URL on your web page; e.g. if it's going to lose them all the data that they've entered on a form there.  The usual way to do this is to use the onclick event to call a JavaScript function to do the work.

Here's an example of such a JavaScript function:

function navigateToNewDoc() {
  if(confirm('This will create a new calculation form, so losing all the values that you have currently set. Continue?')) {
        location.href = "/mydb.nsf/myForm?OpenForm";
  }
}


And here's the HTML code that calls it:
<a href='#' onclick='navigateToNewDoc();'><img src='button_new_01.gif?OpenImageResource' alt='Back' border='0'></a>


The "a href" URL is replaced by a dummy one, because it's no longer used.   Instead, we use the onclick call to the navigateToNewDoc function to forward us to the new URL, but only after the user has clicked "OK" on our warning dialog.

So far, so standard.


Problem

Where this technique comes unstuck is when you try to right click on such a link and have it open in a new window or tab.  In this case the browser will ignore the onclick event and will try to open the actual URL, which in the example above doesn't exist (we replaced it with "#").  Either that or will try to open the JavaScript code itself as the actual URL!!  We'll either get a browser error or at best, it will simply open the current tab's URL in the new tab. You'll see a bazillion examples of this on the interweb every day.  And don't you just hate, hate hate it!  I know I do.

If we try to get around this by restoring the real URL into the "a href=" statement, then we will get the right-click behaviour that we need but that messes up the left-click behaviour!  What will happen now is that the main URL will be always be followed on a left-click, regardless of how we answered the JavaScript confirmation dialog.


Solution

The trick to making it work both ways is to put a "return false;" statement as the last statement of the onclick call.  This prevents the main "a href=" URL from being followed for a left-click (but not for a right-click + Open in New Tab), so leaving the onclick call to take care of the left-click scenario, as it did before.

Here's the revised HTML:

[a href="/mydb.nsf/myForm?OpenForm"  onclick="navigateToNewDoc(); return false;"][img src='button_new_01.gif?OpenImageResource' alt="Back" "border"=0][/a]


Now we can have our cake an eat it too.  We get our warning dialog on a left-click, but can still open the new form in a new tab.
Comments
No Comments Found

About