commit
commit

Reputation: 4807

stop redirecting page if it is redirecting by clicking on anchor

I want to prevent page redirecting I know it can be achieve by this

window.onbeforeunload = function() {
        return "Dude, are you sure you want to leave? Think of the kittens!";
}

which was answered here Prevent any form of page refresh using jQuery/Javascript

But in my case I only want to prevent page when it is redirecting by clicking on any of the anchor tag.

Also event.preventDefault() will not work in my case while clicking on anchor tag because all anchors are not redirecting page so it should work fine.

I only want to stop redirecting page if it is redirecting by clicking on anchor. Any solution?

Upvotes: 3

Views: 8503

Answers (4)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114367

The caller will be null if a link is clicked:

window.onbeforeunload = function() {
    alert(window.onbeforeunload.caller)    
}

Upvotes: 0

Joe Enos
Joe Enos

Reputation: 40393

You can keep a flag which tells you whether or not the user clicked an a tag, then read that on your onbeforeunload script:

window.onbeforeunload = function () {
    if (_clickedAnchor) {
        _clickedAnchor = false;
        return "Dude, are you sure you want to leave? Think of the kittens!";
    }
}

_clickedAnchor = false;

jQuery(document).ready(function () {
    jQuery("a").click(function () {
        _clickedAnchor = true;
    });
});

Upvotes: 4

Jnatalzia
Jnatalzia

Reputation: 1687

So since you tagged jQuery I'll put my solution in terms of that. You can grab all the a tags and then check to make sure the anchor is a redirect, then use the e.preventDefault();

$('a').on('click',function(e){
    if ($(this).attr('href') != window.location.href)
    {
       e.preventDefault();
       //do stuff
    }
});

Upvotes: 0

user1386320
user1386320

Reputation:

You can use onhashchange.

With jQuery:

$(window).on('hashchange', function() {
    alert('bye byee?');
});

Plain DOM JavaScript:

window.onhashchange = function() {
    alert('bye byee?');
};

Note: You will need to create a custom "hash-change" handler for older browser which don't support this event.

You can easly do this with setInterval and detect any changes in document.location.hash.


Failsafe onhashchange for older browsers:

var currentHash = document.location.hash;

window.prototype.onhashchange = function( callback ) {
    if(typeof(callback) == 'function') {
        setInterval(function() {
            if(document.location.hash !== currentHash) {
                callback();
            }
        }, 650); // more than a half-a-second delay
    }
}

And you can use it as an event in regular DOM convention.

Upvotes: 0

Related Questions