stop redirecting page if it is redirecting by clicking on anchor - javascript

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?

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;
});
});

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.

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
}
});

The caller will be null if a link is clicked:
window.onbeforeunload = function() {
alert(window.onbeforeunload.caller)
}

Related

How to disable the browser back button using javascript in a HTML page. Can we get any callback method trigerred on click of backbutton on browser

How to disable the browser back button using javascript in a HTML page. Can we get any callback method trigerred on click of backbutton on browser using Javascript and not using Jquery Mobile library.
Solution would be really appreciated. I tried with few solutions online, but nothing seemed to work.
You should never do that. https://www.irt.org/script/311.htm
By the way, you may just warn the user using window.onbeforeunload.
You can-not actually disable browser back button. And there is no event for capturing the back button click.
If it is really necessary you can do something like that:
(function (global) {
var _extra_hash = "!";
var noBack = function () {
global.location.href += "#";
global.setTimeout(function () {
global.location.href += _extra_hash;
}, 50);
};
global.onhashchange = function () {
if (global.location.hash !== _extra_hash) {
global.location.hash = _extra_hash;
}
};
global.onload = function () {
noBack();
// this is for disabling backspace on page except on input fields and textarea..
/*document.body.onkeydown = function (e) {
var elm = e.target.nodeName.toLowerCase();
if (e.which === 8 && (elm !== 'input' && elm !== 'textarea')) {
e.preventDefault();
}
// stopping event bubbling up the DOM tree..
e.stopPropagation();
};*/
}
})(window);
But the user can still kill the tab. Anyway, It is generally a bad idea overriding the default behavior of web browser.

How to disable window.onbeforeunload from <a> tag?

First I used window.onbeforeunload on my application. It's working on over page but when click on anchor link it should be disabled Click. Any ideas? Please share. My code is below it is not working:
var submitFormOkay = false;
window.onbeforeunload = function () {
if (!submitFormOkay) {
return "Don't delay your Success. Get FREE career counselling session. Fill in the details below";
} else {
submitFormOkay = '';
}
}
<a class="navbar-brand" href="http://www.google.com">Click</a>
You could attach a global click handler on document.body which, if the click passed through an a element, sets submitFormOkay to true (or you could use another variable to bypass the check, or just clear the handler by assigning null to window.onbeforeunload), e.g.:
$(document.body).on("click", "a", function() {
submitFormOkay = true; // Or set another flag you'll check,
// or clear onbeforeunload entirely
});
Without jQuery (since I missed the jquery tag initially):
document.body.addEventListener("click", function(e) {
var element;
for (element = e.target; element != document.body; element = element.parentNode) {
if (element.tagName.toUpperCase() === "A") {
submitFormOkay = true; // Or set another flag you'll check,
// or clear onbeforeunload entirely
break;
}
}
}, false);
using jquery it can be follow:
var submitFormOkay = false;
$(window).on('beforeunload',function () {
if (!submitFormOkay) {`enter code here`
return "Don't delay your Success. Get FREE career counselling session. Fill in the details below";
} else {
submitFormOkay = '';
}
})
<a class="navbar-brand" href="http://www.google.com">Click</a>
$('a').on('click',function(e){
e.preventDefault();
$(window).off('beforeunload');
window.location = $(this).attr('href');
});

.click() not getting fired over an anchor tag after modifying its download attribute

My case is that "System needs to ask to the user that 'are you going to open the image or to download it.?' by using a confirm box.. If user presses okay we should not prevent the default action of that anchor tag, let it go, but if user presses cancel the particular image should get downloaded...
HTML:
test
JS:
$('a').click(function (e) {
if (!$(this).is('[download]')) {
var cond = confirm('Press ok to view, cancel to save..');
if (!cond) {
e.preventDefault();
$(this).attr('download', 'download').click().removeAttr('download');
}
}
});
DEMO
Can anybody tell how to achieve this..?
You need to use this.click(); as HTMLElement.click() method simulates a mouse click on an element.
Whereas $(this).click(); will only trigger jquery click handler and onclick handler bounded to element nothing else.
$('a').click(function (e) {
if (!$(this).is('[download]')) {
var cond = confirm('Press ok to view, cancel to save..');
if (!cond) {
e.preventDefault();
$(this).attr('download', 'download');
this.click()
$(this).removeAttr('download');
}
}
});
DEMO
Try with this, $("a")[0].click() will do the trick
$('a').click(function (e) {
if (!$(this).is('[download]')) {
var cond = confirm('Press ok to view, cancel to save..');
if (!cond) {
e.preventDefault();
$(this).attr('download', 'download');
$("a")[0].click().removeAttr('download');
}
}
});
Demo
$('a').click(function (e) {
if (!$(this).is('[download]')) {
var resp = confirm("Press ok to view, cancel to save..!");
if (resp == true) {
// You pressed OK
e.preventDefault();
} else {
// Pressed Cancel!";
$(this).attr('download', 'download').click().removeAttr('download');
}
}
});
here you go working fiddle
http://jsfiddle.net/sajrashid/94Hra/18/
There is no need to mess with event bubbling with this one. Let the browser's default behavior take care of everything. Calling events manually always creates a mess. Control behavior with the download attribute. Add it or remove it based on your condition and pass the ball to browser.
Demo
Code:
$('a').click(function (e) {
var cond = confirm('Press ok to view, cancel to save..');
if (!cond) {
$(this).attr('download', 'download');
} else {
$(this).removeAttr('download');
}
});
I checked your code and got a solution
So you have to change your code a bit
you have add a name tag in your anchor tag like
test
Now replace your code
$('a').click(function (e) {
With this one
$(document).on("click","a[name='myevent']", function (e) {

External Link Notification - JavaScript or JQuery

I am looking for a way to set it up so that when an external link is clicked it will warn people that they are leaving the site. Preferably, it would darken the screen and display a message in the middle of the screen in a box with the option to click OK or Cancel.
I tried to use this code:
$("a.external").click(function () {
alert("You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.");
});
and give each link a class of external but it doesn't seem to work. I don't want to use this because it means that the client will have to remember to add the class I would prefer something more automatic.
I also tried to use this code to do so but to no avail:
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
})
.click(function () {
var x=window.confirm('You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.');
var val = false;
if (x)
val = true;
else
val = false;
return val;
});
I am using WordPress 3.8.1.
Thanks in advance for any help you can give.
Your filter logic should be correct, Try using the confirm function, and using jQuery instead of $.
jQuery('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).click(function(e) {
if(!confirm("You are about to proceed to an external website."))
{
// if user clicks 'no' then dont proceed to link.
e.preventDefault();
};
});
I tried this out in dev tools on your site and it seems to work correctly if you use jQuery. I think you may have some plugin that is causing conflicts with $.
JSFiddle Demo
Try using confirm instead of alert since that will pause and wait for user input. You'll then need function(e){ e.preventDefault(); } to prevent the default link actions.
To identify just external links you might do something like this:
var ignoreClick = false;
$(document).ready( function(){
$('input[type="submit"], input[type="image"], input[type="button"], button').click(function(e) {
ignoreClick = true;
});
$(document).click(function(e) {
if($(e.target).is('a'))
checkLink(e);
});
$('a').click(function(e) {
checkLink(e);
return true;
});
checkLink = function(e){
// bubble click up to anchor tag
tempTarget = e.target;
while (!$(tempTarget).is('a') && !!tempTarget.parentElement) {
tempTarget = tempTarget.parentElement;
}
if ($(tempTarget).is('a')){
if(!!tempTarget && $(tempTarget).is('a') &&
(tempTarget.hostname == "" || tempTarget.hostname == "#" || tempTarget.hostname == location.hostname)){
ignoreClick = true;
}
}
}
});
and to catch people with a message you might use beforeunload and the confirm option
$(window).bind("beforeunload", function (e) {
if (!ignoreClick){
if(!confirm("Leaving website message")) {
e.preventDefault();
}
}
});
It worked pretty well to me. I just removed unnecesary variables, but original script worked fine.
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
})
.click(function () {
return window.confirm('You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.');
});
http://jsfiddle.net/3dkAN/1/
EDIT
Following #user1308743's line, seems that in cgmp.framework.min.js is summoning the jQuery.noConflict() mode, that unbinds the $() function for jQuery. So please use jQuery() for any jQuery implementation

detect back button click in browser [duplicate]

This question already has answers here:
Intercepting call to the back button in my AJAX application
(12 answers)
Closed 8 years ago.
I have to detect if a user has clicked back button or not.
For this I am using
window.onbeforeunload = function (e) {
}
It works if a user clicks back button. But this event is also fired if a user click F5
or reload button of browser. How do I fix this?
So as far as AJAX is concerned...
Pressing back while using most web-apps that use AJAX to navigate specific parts of a page is a HUGE issue. I don't accept that 'having to disable the button means you're doing something wrong' and in fact developers in different facets have long run into this problem. Here's my solution:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
}
As far as Ive been able to tell this works across chrome, firefox, haven't tested IE yet.
Please try this (if the browser does not support "onbeforeunload"):
jQuery(document).ready(function($) {
if (window.history && window.history.pushState) {
$(window).on('popstate', function() {
var hashLocation = location.hash;
var hashSplit = hashLocation.split("#!/");
var hashName = hashSplit[1];
if (hashName !== '') {
var hash = window.location.hash;
if (hash === '') {
alert('Back button was pressed.');
}
}
});
window.history.pushState('forward', null, './#forward');
}
});
best way I know
window.onbeforeunload = function (e) {
var e = e || window.event;
var msg = "Do you really want to leave this page?"
// For IE and Firefox
if (e) {
e.returnValue = msg;
}
// For Safari / chrome
return msg;
};
I'm detecting the back button by this way:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
It works but I have to create a cookie in Chrome to detect that i'm in the page on first time because when i enter in the page without control by cookie, the browser do the back action without click in any back button.
if (typeof history.pushState === "function"){
history.pushState("jibberish", null, null);
window.onpopstate = function () {
if ( ((x=usera.indexOf("Chrome"))!=-1) && readCookie('cookieChrome')==null )
{
addCookie('cookieChrome',1, 1440);
}
else
{
history.pushState('newjibberish', null, null);
}
};
}
AND VERY IMPORTANT, history.pushState("jibberish", null, null); duplicates the browser history.
Some one knows who can i fix it?
Since the back button is a function of the browser, it can be difficult to change the default functionality. There are some work arounds though. Take a look at this article:
http://www.irt.org/script/311.htm
Typically, the need to disable the back button is a good indicator of a programming issue/flaw. I would look for an alternative method like setting a session variable or a cookie that stores whether the form has already been submitted.
I'm assuming that you're trying to deal with Ajax navigation and not trying to prevent your users from using the back button, which violates just about every tenet of UI development ever.
Here's some possible solutions:
JQuery History
Salajax
A Better Ajax Back Button

Categories