Created
November 10, 2017 14:05
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!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