var showPop = true;
function exitIt(){
if (showPop){
showPop = false;
return 'blah blah';
}
}
This is a little exit pop up. If the user chooses to "stay on the page", I need it to redirect to the proper URL. How can I do this?
Just because you can implement something, doesn't mean that you should. Exit popups are arguably the most annoying thing ever!
or document.location = "http://www.example.com/";
if (confirm('Move to another page?')){
window.location = "http://blah.com/";
}
$("a#myleavinglink").click(function() {
var answer = confirm("Are you sure you should leave? Its so sweet thougH!");
if (answer) {
return true;
} else {
return false;
}
}
You could also do a very similar thing with jQuery and if the user decides to leave the page, or back up, or type in their own address.
BTW, by returning true from a click function in jQuery will allow standard operations, but returning false will override the standard functionality and only provide the functionality you have choosen. Hence, if the user wants to leave, it returns true, else it returns false
$("a").live("click", function() {
var id = $(this).attr("id");
if (id == approvedClicks) {
return true;
} else {
return false;
}
});
that would prevent any links being clicked to be removed, whether at page load, or added in with JS.
Related
I have a project use confirm box javascript, if user click cancel and then do nothing but page still load, i search all about confirm box and i can't find what i looking for, please help me with this, here some code
javascript
function OnClickNextPage(){
var result = confirm("Are you sure ?");
if (!result) {
return false;
}
}
html
Test
Thank you
Instead of returning false you have to prevent the default beahaviour of the event with preventDefault() function. Here is the code
Test
function OnClickNextPage(event){
var result = confirm("Are you sure ?");
if (!result) {
event.preventDefault();
}
}
You have to "terminate" the click event to the a tag, to do this, you have pass the event object to OnClickNextPage function, then call .preventDefault() on the event. return false; action does not affect to onclick event.
HTML
Test
Javascript
function OnClickNextPage(event) {
var result = confirm("Are you sure ?");
if (!result) {
event.preventDefault(); // prevent event when user cancel
}
// go to page in a tag's href when user choose 'OK'
}
try
function OnClickNextPage(e){
e.preventDefault();
var result = confirm("Are you sure ?");
if (!result) {
return false;
}
}
Edit --
Sorry My bad, problem is you are calling page load event in href which eventually fire on priority of DOM
Test
Try like this
Test
function OnClickNextPage(e){
e.preventDefault();
var result = confirm("Are you sure ?");
if (!result) {
return false;
} else {
window.location.href = [[Your URL Here]]
}
}
JS
function OnClickNextPage(e){
console.log('after prevent')
var result = confirm("Are you sure ?");
if (!result) {
e.preventDefault();
return false;
}
}
HTML
Test
window.onbeforeunload = function(evt) {
var message = 'Are you sure you want to leave the page. All data will be lost!';
if (typeof evt === 'undefined') {
evt = window.event;
}
if (evt && !($("#a_exit").click)) {
evt.returnValue = message;
}
return message;
};
I want user to leave the page clicking to the link (has id ="a_exit") only. In other circumstances such as refreshing the page, clicking another link, user will be prompted that if he/she wants to leave the page. I have tried to use the code above. It still asks me if I want to go away when I click the exit link.
$(window).bind('beforeunload',function() {
return "'Are you sure you want to leave the page. All data will be lost!";
});
$('#a_exit').live('click',function() {
$(window).unbind('beforeunload');
});
Above works for me
My quick example of the conditional prompt before leaving page:
window.onbeforeunload = confirmExit;
function confirmExit(event) {
var messageText = tinymce.get('mMessageBody').getContent();
messageText = messageText.trim();
// ... whatever you want
if (messageText != "")
return true;
else
return void (0);
};
It works under Chrome, FF.
You can return null when you do not want the prompt to show. Tested on Chrome 79.
window.onbeforeunload = () => {
if(shouldPrompt){
return true
}else{
return null
}
}
BTW modern browser no longer support custom onBeforeUnload promp text.
It will always prompt you if you want to leave the page. It's a security issue and cannot be worked-around.
Moreover, anything you return in the onbeforeunload event handler that is not void will be treated as the message for the prompt. Refer to this article: https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload
This worked for me.
window.onbeforeunload = function(){
if(someBoolean) {
return 'message'
}else{
window.onbeforeunload = null;
}
}
You could just remove window.onbeforeunload in the click handler.
How about a variable to decide, if the link was clicked?
var exitClicked = false;
$("#a_exit").click(function() {
exitClicked = true;
});
window.onbeforeunload = function(evt) {
//...
if(evt && !exitClicked) {
evt.returnValue = message;
}
//...
};
You only set exitClicked = true when the link was really clicked and afterwards, before unloading you can simply check this variable.
This is quite old but I wanted just to change the code given that .live is no longer working in Jquery. So, the updated version would be:
$(window).bind('beforeunload',function() {
return "'Are you sure you want to leave the page. All data will be lost!";
});
$('#a_exit').on("click", function(){
$(window).unbind('beforeunload');
});
have a href as follows:
<a class="eLink" href="http:www.abc.com">chk here xyz</a></li>
and javascript for "eLink" is as follows:
$("a.eLink").click(function link(evt) {
url = evt.target.href;
if (url.toString().toLowerCase().indexOf(".gov") <= 0) {
var tk = "Do you really want to continue?";
if (confirm(tk)) {
window.open(url, 'newwin');
}else{
window.open(url,'_self');
}
}
else
{ window.open(url, 'newwin'); }
return false;
});
});
Now my issue is when i click the href and click 'cancel' in the confirm button, my page goes to "abc.com", but it shouldnt happen. My browser should remain the same. what script should i use in the else part so i remain the same page. thanks.
Just take the else out.
if (confirm(tk)) {
window.open(url, 'newwin');
}
Sidenote, IE8 and lower doesn't implement the indexOf function so you may want to patch it by writing your own implementation.
the default action should already be prevented by return false; (jQuery style)
the problem is that if you click cancel window.open(url,'_self'); is executed, just remove the else part of the confirm condition
check this fiddle
You have:
var tk = "Do you really want to continue?";
if (confirm(tk)) {
window.open(url, 'newwin');
}else{
window.open(url,'_self');
}
This means that if they click cancel, False will be returned, which will still open the link. You need to remove window.open in your else statement
if (confirm(tk)) {
window.open(url, 'newwin');
}
i have a page on which i want to confirm if the user wants to leave.
i have to confirm only when a certain condition is met so i wrote code like this
var back=false;
back=//check if user pressed back button
window.onbeforeunload = function (e) {
alert(back); //this alerts true
if(back==true)
return false;
//e.preventDefault; --this does not work too
};
but this does not work. i mean when i click on back button this onbeforeunload still fires and i still get the confirmation message even when i m returning false.Whats can be wrong?
Thanks
Return a string if you want to offer an option to the user to abort the unload. Return nothing in other cases.
var back = false;
back = true; //Somewhere, the condition is set to true
window.onbeforeunload = function (e) {
if(back == true)
return "Are you sure to exit?";
}
$(window).bind('beforeunload',function() {
return "'Are you sure you want to leave the page. All data will be lost!";
});
$('#a_exit').live('click',function() {
$(window).unbind('beforeunload');
});
Try this. Above code is working in most of conditions.
For the sake of completeness here a more modern, recommended approach:
let warn = false;
window.addEventListener('beforeunload', e => {
if (!warn) return;
// Cancel the event
e.preventDefault();
// Chrome requires returnValue to be set
e.returnValue = '';
});
warn = true; // during runtime you change warn to true
Typically, it is better to use window.addEventListener() and the
beforeunload event, instead of onbeforeunload.
Source
The reason why your originally posted code didn't work is that false is a non-null value. If you would have returned null or undefined in the situation where you don't want to spawn a pop-up warning your code would have worked as expected.
The currently accepted answer works because JavaScript implicitly returns undefined at the end of the function.
Condition for back-end
var confirmExist = function (e) {
return true;
}
window.onbeforeunload = confirmExist;
http get, post request
.then(function(r)) {
window.onbeforeunload = null;
}
You could also consider not setting the window.beforeunload event untill your list of conditions are met.
var confirmUserToLeave = function () {
if (/* conditions are met */) {
window.unbeforeunload = function (e) {
/* whatever you want to do here */
};
} else {
window.unbeforeunload = undefined;
}
};
Then just call that method on certain events that might change the outcome of your 'conditions are met'.
I have set up in javascript:
var onBeforeUnloadFired = false;
window.onbeforeunload = function (sender, args)
{
if(window.event){
if(!onBeforeUnloadFired) {
onBeforeUnloadFired = true;
window.event.returnValue = 'You will lose any unsaved changes!'; //IE
}
}
else {
return 'You will lose any unsaved changes!'; //FX
}
windows.setTimeout("ResetOnBeforeUnloadFired()", 1000);
}
function ResetOnBeforeUnloadFired() {
//Need this variable to prevent IE firing twice.
onBeforeUnloadFired = false;
}
I'm trying to achieve an edit screen where the user is warned before navigating away. It works fine except I get the pop up for normal post backs of button clicks. I'm hoping to avoid this so I'm figuring if I could determine which button was pressed it would work.
Does anybody know how to determine which button was pressed in the windows.onbeforeunload?
Alternatively anyone know a better approach to what I'm trying to achieve?
Solved this by putting into an update panel all edit items TextBoxes etc.
Now the windows.onbeforeunload only fires for components external to this.
Another method, if you can't "control" that deep you controls, is to mark somewhat the "good controls", that is the ones which should not trigger the away-navigation logic.
That is easily achievable setting a global javascript variable such as
var isGoodLink=false;
window.onbeforeunload = function (e) {
var message = "Whatever";
e = e || window.event;
if (!isGoodLink) {
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
}
};
function setGoodLink() {
isGoodLink=true;
}
And add the setGoodLink function on the events you want to keep safe:
<button type="button" onclick="javascript:setGoodLink() ">I am a good button!</button>