Skip to content

Instantly share code, notes, and snippets.

@stephanbogner
Created November 10, 2017 14:05
Show Gist options
  • Select an option

  • Save stephanbogner/899b76f56194c9cbd38bf8f0478bac0c to your computer and use it in GitHub Desktop.

Select an option

Save stephanbogner/899b76f56194c9cbd38bf8f0478bac0c to your computer and use it in GitHub Desktop.
Simple example to check if a user leaves a browser window and show some information
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<style type="text/css">
body {
background-color: #ECECEC;
font-family: sans-serif;
font-size: 1.5rem;
padding: 4rem;
}
#popup {
width: 50vw;
height: 50vw;
background: white;
padding: 1rem;
margin: 9rem auto 0 auto;
position: relative;
}
#close{
position: absolute;
right: 1.2rem;
top: 1rem;
}
#close:hover{
cursor: pointer;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
Click into the url bar.
<div id="popup" style="display:none">
You are leaving? <span id="close">×</span>
</div>
<script type="text/javascript">
var timer;
init();
function init() {
var title = {
'original': $(document).find('title').text(),
'leaving': 'See you soon',
'returning': 'Welcome back'
}
setListeners('#popup');
function setListeners(message) {
var popup = $(message);
window.onblur = function() {
changeTitle('leaving', title);
showPopup(popup);
}
window.onfocus = function() {
changeTitle('returning', title);
}
$('#close').click(function() {
hidePopup(popup);
});
}
}
function showPopup(popup) { popup.show(); }
function hidePopup(popup) { popup.hide(); }
function changeTitle(state, title) {
switch (state) {
case 'leaving':
document.title = title.leaving;
clearTimeout(timer);
break;
case 'returning':
document.title = title.returning;
timer = setTimeout(function() { changeTitle('', title) }, 3000);
break;
default:
clearTimeout(timer);
document.title = title.original;
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment