Clicking 'cancel' in confirm() method has the same result as clicking 'ok' - javascript

I am a beginner implementing a confirm method in my HTML code - when the user clicks on "x", they will be redirected to the home page. Otherwise, nothing happens.
My problem is that in confirm(), both "ok" and "cancel" options redirect to home page and I cannot figure out why.
I saw that many people have a similar problem, checked many forums and noticed that writing onclick="return confirmCancel() rather than onclick="confirmCancel()" helped in most of the cases but it did not solve the problem for me.
HTML:
<a onclick="return confirmCancel()"><img src="assets/cancel.svg"></a>
JS:
const confirmCancel = () => {
confirm("All your progress will be lost. Are you sure you want to leave?");
if (confirmCancel) {
window.location.assign("index.html");
} else {
return false;
}
}

You need to test the return value of confirm (rather than the truthiness of the confirmCancel function).
const confirmCancel = () => {
if (confirm("All your progress will be lost. Are you sure you want to leave?");) {
window.location.assign("index.html");
} else {
return false;
}
}

Try something like this.
<a onclick="pleaseConfirm"><img src="assets/cancel.svg"></a>
const pleaseConfirm = () => {
if (confirm("All your progress will be lost. Are you sure you want to leave?")) {
window.location.assign("index.html");
}
}

You're mostly there .. You need to check if confirm() is true .. Change:
confirm("All your progress will be lost. Are you sure you want to leave?");
if (confirmCancel)
To
var test_confirm = confirm("All your progress will be lost. Are you sure you want to leave?");
if (test_confirm === true)
Shorthand can be
if (confirm("All ... ... "){

You can do the functionality inside JavaScript instead of calling out JavaScript function in your HTML tag
<a id="btn-exit"><img src="assets/cancel.svg"></a>
var btnExit = document.querySelector('#btn-exit')
btnExit.addEventListener('click', () => {
if (confirm("are you sure?")) {
window.location.assign("index.html");
}
})

Related

JavaScript ignore alert if reloading page

I am detecting the end of a webrtc stream in JavaScript like this...
stream.getVideoTracks()[0].onended = () => {
alert('Feed Has Ended');
};
This is working correctly, but if the user refreshes or reloads the page then the alert is also shown.
I understand that this is technically correct, but how can I get it to not display the alert under those conditions?
Why don't you use a global boolean to check if video is playing or not? When you will reload or refresh the page, isVideoRunning will become false and alert won't show.
Like
this.isVideoRunning = false;
On addtrack,
this.rtcPeerCon_.ontrack = function (event) {
if (!this.rtcPeerCon_) {
return;
}
if( !this.remoteVideo_ ) {
return;
}
this.remoteVideo_.srcObject = event.streams[0];
this.isVideoRunning = true;
}
then in your onStream ended callback you can check
if (this.isVideoRunning) {
alert('whatever');
this.isVideoRunning = false;
}
(I wanted this to be comment but I am not allowed to comment yet)

Javascript onUnload Show offer and redirect to offer page if stays on page [duplicate]

Rewriting the question -
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload handeler saying we have a great offer for you? and if user choose to leave the page it should do the normal propogation but if he choose to stay on the page I need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
but the problem is that if he click on the link to yahoo.com and choose to leave the page he is not going to yahoo but to google instead :(
Help Me !! Thanks in Advance
here is the fiddle code
here how you can test because onbeforeunload does not work on iframe well
This solution works in all cases, using back browser button, setting new url in address bar or use links.
What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler.
In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/
EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
It's better to Check it local.
Check out the comments and try this: LIVE DEMO
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
And change your html code to this:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
try it
</body>
After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.
jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
Try the following, (adds a global function that checks the state all the time though).
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
<script>
function endSession() {
// Browser or Broswer tab is closed
// Write code here
alert('Browser or Broswer tab closed');
}
</script>
<body onpagehide="endSession();">
I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...
Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)
Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.

listening for click event for an href by classname

there is a page with some basic HTML that I cannot touch that looks like this:
<a class="continue-shopping" href="https://someURL">Continue shopping</a>
what I want to do is send the user to a different link when they click on the someURL text link. the user can come to a page containing this html from many other pages.
i have tried many hours but cannot get my js to recognize a click event for a class associated with hyperlinked text. i could really use some help here. this is the js code i wrote which does not work
window.onload = function() {
prepEventHandler();
}
function prepEventHandler () {
var myClass = document.getElementsByClassName("continue-shopping");
myClass[0].onclick=window.open(document.referrer,"_self");
/* which make my pages go haywire OR THIS -- which also does not work */
myClass[0].addEventListener("click", function() {
window.open(document.referrer,"_self");
}
)
}
It just keeps ignoring the second function, and I am sure I am doing some really basic that is wrong. Again, thanks for any help!
Apart from preventDefault() you could also use return false
window.onload = function () {
var myClass = document.querySelector(".continue-shopping")
.onclick = function () {
window.location.href = "http://elsewere.com";
return false;
}
}
this code should work but it no longer does and i do not know why any hint much appreciated - there seems to be some problem with myClass[0]
window.onload = function() {
var myClass = document.getElementsByClassName('continue-shopping');
myClass[0].addEventListener("click", function(e) {
e.preventDefault();
window.location.href = document.referrer;
});
}

FormNavigate with confirm box yes no button

When a user leaves a JSP page, I need to display a confirmation with yes no button "You have unsaved changes. Do you want to leave it without saving?". If the user presses "ok", then the user goes to the page s/he is navigating to. Otherwise, if "no" is pressed, the user stays on the page. My code is here:
var formdata_original=false;
jQuery(".outConfirmPlugin").click(function () {
if (formdata_original == false) {
con();
}
return formdata_original;
});
function con() {
$.confirm({
'title':'',
'message':settings.jsMessage,
'buttons':{
'Yes':{
'class':'blue',
'action':function () {
formdata_original = true;
}
},
'No':{
'class':'gray',
'action':function () {
}
}
}
});
};
I know my error is: function "con" and "return formdata_original;" - they are not synchronized. How can i do this?
try return simple value from you function, i mean
action':function () {
return true;
}
and when you call 'con' function you will be able to write
formdata_original = con();
In this case you can not worry about sinhronize
The second option is creation global object that belongs ot window or $. So try
window["formdata_original"] = false
and in your code inside confirm dialog
window["formdata_original"]=true.

setting the variable of js function from within htm

I am creating a simple function that warns the user when they are about to close out of a web page. I am using the window.onbeforeonload function is javascript. What I am doing is that, I set a variable to false because of the evil window.onbeforeonload function.
function funky() {
var submitFormOkay = false;
window.onbeforeunload = function () {
if (submitFormOkay == false) {
return "You are about to leave this order form. You will lose any information...";
}
}
}
In my html, this is what I am doing
<input type="submit" id="submit_button" onclick="submitFormOkay = true;">
My question however is that I need a way to fire the function funky().
I know I could use an onclick but if I do what is going to set the value of submitFormOkay.
Any help would be appreciated.
Why not make submitFormOkay a parameter of the function funky, and just call it with the given parameter?
<input type="submit" id="submit_button" onclick="funky(true);">
And in the JS file:
function funky(submitFormOkay) {
window.onbeforeunload = function () {
if (submitFormOkay == false) {
return "You are about to leave this order form. You will lose any information...";
}
}
}
Without changing your HTML, I'd do this instead:
window.onbeforeunload = (function(w) {
w.submitFormOkay = false;
return function() {
if (!w.submitFormOkay) {
return "You are about to leave this order form. You will lose any information...";
}
};
})(window);
​A problem with ngmiceli's solution is that window.onbeforeunload's callback never gets defined until the user is okay to leave the page.

Categories