Jquery – window.onbeforeunload in javascript

clickjqueryonbeforeunload

I'm using javascript window.onbeforeunload function to show an alert to user whenever user tries to leave the page without submitting the data. This functinality is working fine.

Problems comes in IE (only) where the window.onbeforeunload event fires even on click of internal links like

<a class="editlink" onclick="fnEditLink(this);" href="javascript:void(0);" > <img src="/images/newstyle/pencil.png" alt="edit" /> Edit </a>

This is an internal link that is used to edit grid row without making any redirection or ajax call. Just a plain simple edit of newly created row in html DOM structure.

This is the javascript code that I've used in the page:

<script>
var is_clicked = false;
$(document).ready(function(){
    $('#get-a-quote-step2').submit(function(){
        is_clicked = true;
        return validate('get-a-quote-step2');
    });
    $('#skip_step, form input').click(function(){is_clicked = true;});
});

window.onbeforeunload = function() {

    if(!is_clicked)
        return false;
}
is_clicked = false;
<script>

Everything is working fine on firefox but on IE it is creating problem.
I'm using IE 8 for testing this stuff, but I guess problem is with alll versions of IE.

In my above code, problem is if I click on an internal link it sets is_clicked flag to true and then if I press refresh button, I'm able to reload the page without asking user that is he leaves he will loose all unsaved data.

I was thinking if there is anyway esp; in JQuery so that we know if some particular links are not clicked some thing like isNotClicked() ? Or if there is any other solution to my problem it is most welcome.

Best Answer

So if you just want to prevent certain links from firing the onbeforeunload event you can simple return false inside of your click event declaration...

<a href="http://google.com">Call unload first and load a page</a>
<a href="javascript:void(0);" id="request">Do an ajax request</a>
<script>
$(document).ready(function(){
    $('#request').click(function(e){
        //do some stuff
        //returning false wil prevent the onbeforeunload event from firing
        //but also will not redirect if the link has an href
        return false;
    });
});
window.onbeforeunload = function(e){
        return 'Want to leave?';
}

</script>