(Like some of the other answers, this requires changing how the JavaScript is bound. If that doesn't work for you, disregard.)
I found that in IE 7 through IE 10, simply using jQuery .click() with preventDefault
works without showing the onbeforeunload
message (IE 11 does not show the beforeunload
message for any of my test cases). This is true whether the href is '#' or javascript:void(0)
. I expect the conclusion holds if attachEvent
/addEventListener
is used directly, but I didn't test that.
There is a demo of the below at http://jsbin.com/tatufehe/1 . Both of the versions (in green) with preventDefault
work (don't show the beforeunload
dialog). The one without preventDefault
does show it (as a comparison).
$( document ).ready( function () {
$( 'a' ).click( function ( evt ) {
$( '#display' ).text( 'You clicked: ' + $( this ).text() );
if ( $(this).hasClass( 'withPreventDefault' ) ) {
evt.preventDefault();
}
} );
})
window.onbeforeunload = function () {
return "Are you sure you want to leave?";
};
<p id="display"></p>
<p><a class="withPreventDefault" href="#">Number sign link *with* preventDefault</a></p>
<p><a class="withPreventDefault" href="javascript:void(0);">JavaScript href link *with* preventDefault</a></p>
<p><a href="javascript:void(0);">JavaScript href link *without* preventDefault</a></p>