popup close after back button is clicked - javascript

I am trying to achieve that if popup open and user cancel it and press back it should not again open popup inside it should get back!
<script>
window.onload = function() {
setTimeout(function() {
window.open( "#popup_flight_travlDil3" ,"_self")
}, 1000);
}
</script>

You can use sessionStorage
window.addEventListener("DOMContentLoaded", function() { // or $(function() { ... in jQuery
const popped = sessionStorage.getItem("popped");
if (popped) return;
setTimeout(function() {
window.open("#popup_flight_travlDil3", "_self")
sessionStorage.setItem("popped",true)
}, 1000);
})

Related

Javascript popup when idle, only after a button is clicked

I'm trying to create a popup when a user is idle for (x) seconds and the idle timer only starts after a button is clicked but the timer is reset if there is mouse movement or another click. I also want this popup to only occur 1 timer per session.
So far I have the function working when the button is clicked and the popup shows up after 3 seconds. I would like the timer to be able to be reset when the mouse moves or is clicked.
Here's my javascript
function idlePop() {
var timer = 3000;
function resetTimer() {
}
$(document).ready(function() {
if (!sessionStorage.getItem('popupPreviouslyShown') || false) {
setTimeout(function() {
$('#donate-overlay').css('display', 'block');
sessionStorage.setItem('popupPreviouslyShown', true);
}, timer);
}
});
}
And the html button if you wanted to see it
<button onclick="idlePop();">Start</button>
I'm getting choked up on the function to reset the timer on mouse move (onmousemove) and on mouse click. Any help would be extremely appreciated.
i propose a solution , we'll see with what you say:
i suggest you to replace
<button onclick="idlePop();">Start</button>
by
<button id="start">Start</button>
user clicks on start button and after an idle of 3sec the popup appears
UPDATED V1.0
$(document).ready(function() {
var stage = 0;
var timer = 3000;
var timout = -1;
var isDetectionActivated = false;
$("#start").on('click', function(e) {
$("#start").prop("disabled", true);
//e.stopPropagation();
console.log("start");
idlePop();
})
function activateDetection() {
isDetectionActivated = true;
$(document).on("mousemove click", function(e) {
console.log("timeout aborted")
// you couldt test the type of event with e.type
clearTimeout(timout);
//console.log("you have moved or clicked", e.type);
//re-launch process
idlePop();
});
}
function desactivateDetection() {
$(document).off("mousemove click");
isDetectionActivated = false;
}
function idlePop() {
console.log("idlePop");
//for debuging
/*
timout = launchTimeout(timer);
return;
*/
if (!sessionStorage.getItem('popupPreviouslyShown') || false) {
timout = launchTimeout(timer);
}
}
function launchPopup() {
console.log("popup");
$('#donate-overlay').css('display', 'block');
sessionStorage.setItem('popupPreviouslyShown', true);
}
function launchTimeout() {
if (!isDetectionActivated) {
activateDetection();
}
console.log("timeout activated");
return setTimeout(function() {
console.log("timeout finished");
$("#start").prop("disabled", false);
clearTimeout(timout);
desactivateDetection();
launchPopup();
}, timer);
}
});

changing window.location.hash creates entry in history but doesn't affect chrome back button

Update :- As Akansh Gulati Pointed out in his answer if user have any interaction with the page before clicking back button this will work as expected and if user do not have any interaction with the page and press back button then any entry in history ( either by hash-change or by history.push/replace ) will be ignored which is part of Google Chrome update will stop websites hijacking your browser back button
This is valid and logical answer so I am accepting his answer
I am trying to show a success popup after page load and if user press android back button ( which is in this case equivalent to browser back button ) I only want to close the popup ( don't want to redirect back on payment page )
I am adding hash in url when popup is open but when user press back button chrome ignore the hash and redirect back on previous page instead of just removing the hash ( working fine in Firefox )
I have a working example here use following HTML code to reproduce
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body onload="test()">
<button type="button" onclick="window.history.back();">Back</button>
</body>
<script type="text/javascript">
function writeLength() {
document.body.appendChild(document.createTextNode(window.history.length));
}
function test() {
window.location.hash = 'a';
setTimeout(function() {
writeLength();
window.location.hash = 'b';
setTimeout(function() {
writeLength();
window.location.hash = 'c';
setTimeout(function() {
writeLength();
}, 1500);
}, 1500);
}, 1500);
}
</script>
</html>
a) open this page in chrome
b) wait till hash is changed to '#c'
c) then press browser back button
expected behavior is it should change the hash back to '#b' and then back to '#a'
but it ignore all the hash changes and redirect back to new-tab page
This is the code
window.location.hash = 'a';
setTimeout(function() {
writeLength();
window.location.hash = 'b';
setTimeout(function() {
writeLength();
window.location.hash = 'c';
setTimeout(function() {
writeLength();
}, 1500);
}, 1500);
}, 1500);
how can I simulate the correct behavior (if there is any way) ?
I am using chrome Version 77.0.3865.90 (Official Build) (64-bit) on Mac
here is a GIF image of behavior
In this browser you need to explicitly set at least one state in the History through the History API (not sure why though).
The example should work even in this iframe.
history.replaceState( {}, '' );
window.location.hash = 'a';
setTimeout(function() {
console.log( location.hash );
window.location.hash = 'b';
setTimeout(function() {
console.log( location.hash );
window.location.hash = 'c';
setTimeout(function() {
console.log( location.hash );
console.log( "You can now use your browser's back button" );
onpopstate = e => console.log( location.hash );
}, 150);
}, 150);
}, 150);
I tried using pushState for further location changes and the problem seems solved. No need to replaceState. The condition is only that user must have clicked/interacted atleast once with screen.
function test() {
window.location.hash = 'a';
setTimeout(function () {
writeLength();
window.history.pushState(null, null, `${window.location.pathname}#b`);
setTimeout(function () {
writeLength();
window.history.pushState(null, null, `${window.location.pathname}#c`);
setTimeout(function () {
writeLength();
}, 1500);
}, 1500);
}, 1500);
}
You have to set your state explicitly, and you can execute some code when you click the back button, like this:
Add a function to get the window.location.href without the hash part (because we will add it explicitly):
function getUrlWithoutTheHash() {
let url = window.location.href;
let hash = window.location.hash;
let index_of_hash = url.indexOf(hash) || url.length;
return url.substr(0, index_of_hash);
}
Add a function to push state (rather than changing the hash using the location, we change it using the state API) and we will add an attribute is-my-state to the state to know if this is our state or not:
function pushTheState(url) {
history.pushState({'is-my-state': true, 'url': url}, null, url);
}
And add a handler when you open the state, and if this was one of your states, you can execute a desired code:
window.onpopstate = function(e){
if(e.state){
if(e.state.hasOwnProperty('is-my-state')){
writeLength();
}
}
};
Finally, you need to change your function like this:
function test() {
pushTheState(getUrlWithoutTheHash() + '#a'); // pushing url with #a
setTimeout(function() {
writeLength();
pushTheState(getUrlWithoutTheHash() + '#b'); // pushing url with #b
setTimeout(function() {
writeLength();
pushTheState(getUrlWithoutTheHash() + '#c'); // pushing url with #c
setTimeout(function() {
writeLength();
}, 1500);
}, 1500);
}, 1500);
}
I'm able to get the code your provided working on the same version of Chrome on Windows 10, but if you're still having issues the following should work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body onload="test()">
<div id="url"></div>
<button type="button" onclick="window.history.back();">Back</button>
</body>
<script type="text/javascript">
setInterval(function(){
document.getElementById('url').innerHTML = window.location.href;
}, 500);
function writeLength() {
document.body.appendChild(document.createTextNode(window.history.length));
}
function test() {
history.pushState({},'','#a');
setTimeout(function() {
writeLength();
history.pushState({},'','#b');
setTimeout(function() {
writeLength();
history.pushState({},'','#c');
setTimeout(function() {
writeLength();
}, 1500);
}, 1500);
}, 1500);
}
</script>
</html>
This should work because window.pushState should force the hash change to be added to the browser's history. If you want to update the page of a navigation change, you can use the window.onpopstate event. For example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body onload="test()">
<div id="url"></div>
<button type="button" onclick="window.history.back();">Back</button>
<span id="lengths"></span>
</body>
<script type="text/javascript">
setInterval(function(){
document.getElementById('url').innerHTML = window.location.href;
}, 500);
var last = false;
var items = [];
function writeLength() {
items.push(window.history.length);
document.getElementById('lengths').appendChild(document.createTextNode(window.history.length));
}
function test() {
history.pushState({},'','#a');
setTimeout(function() {
writeLength();
history.pushState({},'','#b');
setTimeout(function() {
writeLength();
history.pushState({},'','#c');
setTimeout(function() {
writeLength();
last = true;
}, 1500);
}, 1500);
}, 1500);
}
window.onpopstate = function(){
if (last) {
if (window.location.hash == '#a') document.getElementById('lengths').innerHTML = items[0];
else if (window.location.hash == '#b') document.getElementById('lengths').innerHTML = '' + items[0] + items[1];
else if (window.location.hash == '#c') document.getElementById('lengths').innerHTML = '' + items[0] + items[1]+ items[2];
}
}
</script>
</html
The code above allows the user to navigate to different "states" of the page after the final length has been written to the document.

auto submit and refresh once

Pls help me to modify this one I want it to submit and refresh only once not every 10sec
<script type="text/javascript">
window.onload=function(){
var auto = setTimeout(function(){ autoRefresh(); }, 100);
function submitform(){
document.forms["myForm"].submit();
}
function autoRefresh(){
clearTimeout(auto);
auto = setTimeout(function(){ submitform(); autoRefresh(); }, 10000);
}
}
</script>
window.onload = function() {
if (window.location.hash !== '#done') {
document.forms['myForm'].submit()
window.location.hash = 'done'
window.location.reload()
}
}
This will submit the form and reload the page only once. The hash will check the URL if it's already been submitted.
You can use local storage to check if the page is being loaded for the very first time.
$(function() {
var canSubmit = localStorage.getItem("can_submit");
if(!canSubmit) {
// first time loaded!
document.forms['myForm'].submit();
localStorage.setItem("can_submit","1");
window.location.reload();
}else{
//You can remove it if needed
localStorage.removeItem("can_submit");
}
});

Confirm box on browser back button

I want to catch the event on back or refresh button of browser. I didn't found any perfect solution that catches only back event and which is compatible with all browsers. please provide some solution.
Thanks in advance.
You can use the event handler onpopstate from HTML5 history API, like this :
$(document).ready(function() {
if (window.history && window.history.pushState) {
$(window).on('popstate', function() {
//confirmation box
confirm('Back button clicked!');
});
}
});
Note that you need to have a page to go back to...
window.userInteractionTimeout = null;
window.userInteractionInHTMLArea = false;
window.onBrowserHistoryButtonClicked = null; // This will be your event handler for browser navigation buttons clicked
$(document).ready(function() {
$(document).mousedown(function() {
clearTimeout(window.userInteractionTimeout);
window.userInteractionInHTMLArea = true;
window.userInteractionTimeout = setTimeout(function() {
window.userInteractionInHTMLArea = false;
}, 500);
});
$(document).keydown(function() {
clearTimeout(window.userInteractionTimeout);
window.userInteractionInHTMLArea = true;
window.userInteractionTimeout = setTimeout(function() {
window.userInteractionInHTMLArea = false;
}, 500);
});
if (window.history && window.history.pushState) {
$(window).on('popstate', function() {
if (!window.userInteractionInHTMLArea) {
//document.location.href = "logOff.htm";
setTimeout(function(){ var answer = confirm("Are you Sure?? This will expire your session");
if(answer == true)
{
document.location.href = "logOff.htm";
}
},100 );
//alert('Browser Back or Forward button was pressed.');
}
if (window.onBrowserHistoryButtonClicked) {
window.onBrowserHistoryButtonClicked();
}
});
}
});

Stopping a timer

I have this JSFiddle that I am working on, and when my mouse leaves the textarea, it closes. But, I can't find a way to cancel this timer if I hover back over it. I've even tried some examples from here. This is the code that closes the text box --
function close() {
setTimeout(function() {
$(Img).css("transform", "rotateX(0deg)");
$(Txt).css("transform", "rotateX(90deg)");
}, 1000);
}
$(Txt).on("mouseleave", function() {
close();
$(Txt).blur();
});
The link you posted from W3Schools has exactly what you need...
setTimeout() returns a reference value, which you can pass to clearTimeout() later to cancel the timer.
var timerID; //set outside the function
function close() {
timerID = setTimeout(function() {
$(Img).css("transform", "rotateX(0deg)");
$(Txt).css("transform", "rotateX(90deg)");
}, 1000);
}
$(Txt).on("mouseleave", function() {
close();
$(Txt).blur();
});
//somewhere else do this...
clearTimeout(timerID);
setTimeout function returns you the handler which you can later use to reset the timer.
For example,
var myVar;
function myFunction() {
myVar = setTimeout(function(){ alert("Hello") }, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
Have you tried:
var myTimeout;
function close() {
myTimeout = setTimeout(function() {
$(Img).css("transform", "rotateX(0deg)");
$(Txt).css("transform", "rotateX(90deg)");
}, 1000);
}
$(Txt).on("mouseleave", function() {
close();
$(Txt).blur();
}).on("mouseenter", function() {
clearTimeout(myTimeout);
});

Categories