Sora
Sora

Reputation: 2551

detect if the user have an intention to redirect from it's page

How can I detect if a user has any intention to leave his current page and redirect to any page from my website is their any javascript function that can handle this event I have more than 25 links in my page

<script type="text/javascript">
if(//user clicks a link )
 confirm("do you want to continue ?"); 

</script>

Is their any javascript function that can check if the user click on any link on the page

Upvotes: 1

Views: 228

Answers (2)

Shankar Cabus
Shankar Cabus

Reputation: 9792

window.onbeforeunload = function(e) {
    return 'Are you sure you want to leave?';
};

Bear in mind that this isn't a normal event - you can't bind to it in the standard way.

To check for values? That depends on your validation framework.

In jQuery this could be something like (very basic example):

$('input').change(function() {
    if( $(this).val() != "" )
        window.onbeforeunload = function(e) {
            return 'Are you sure you want to leave?';
        };
});

Upvotes: 1

jfriend00
jfriend00

Reputation: 708036

This code will intercept all clicks on links in your page.

$("a").click(function() {
    // this.href will be the href of the link they clicked on
    // return false from this function if you want to abort the click on the link
});

FYI, unless there are very special circumstances in your page, it's kind of obnoxious to force a user to confirm that they actually want to go to the link they just clicked on. Can you imagine how terrible the web browser would be if you had to confirm every click.

There is also a generic way to prompt if the user wants to leave your page using the onbeforeunload event.

window.onbeforeunload = function(e) {
    return 'Are you sure you want to leave?';
};

Note: this is also obnoxious unless there are very special circumstances.

Upvotes: 4

Related Questions