The issue

A few months back I came across a rather unusual bug. I was using image buttons on which I had registered client-side onclick events. However, I did not want the buttons to initiate a postback when the user did not confirm the action so I used the usual return false;.

<a href="#" onclick="if(confirm('Are you sure?')==false){return false;} alert('You are sure.');" >Test</a>

I'll use anchor links in my examples, the behavior is not related to buttons, but to the JavaScript.

The issue with the line above is that under some circumstances IE7 does not execute the return false; as expected and will follow the link. Note that this is a very rare bug that you probably won't experience. The bug is not related to a particular build of IE7 because none of my coworkers experience the bug and we all use the latest version of IE7.

There is hope

After searching for a while for a solution, I found this little ray of hope.

event.returnValue = false;

This event property tells the current ongoing event (the click) not to go through once it has finished executing the onclick script.

Under IE7, just using this property works. JavaScript code following this snippet will execute, but the link or button won't behave as if they had been clicked. Under Firefox, the link or button will be clicked.

So now, all I have to do is to set the event.returnValue property to false every time I want to cancel a click event. Wrong, I've had issues while having both the event.returnValue property set to false and returning false at the same time in Firefox.

<a href="#" onclick="event.returnValue = false;return false;">Test</a>

The bottom line

To end all my problems, I've written a JavaScript function that handles all those cases:

  Returns false to prevent postbacks correctly for all browsers*.

  *Currently tested with:
    - Firefox 3.0.3
    - IE 7.0

    - jQuery

  Note: Not all IE browsers have the issue so if "return false" works properly
  in your version of IE7, it does not mean it works properly for everyone.
function CrossBrowserFalse()
    // Check for Internet Explorer
    if (jQuery.browser.msie)
        // Only execute for Internet Explorer, on some computers the browser will submit the button anyway
        event.returnValue = false;

    return false;

And now, all I have to do is call this method instead of returning false:

<a href="#" onclick="return CrossBrowserFalse();">Test</a>