The JS script presented in this page can be used to execute a JavaScript function when the page visibility state changes (when it is opened another window, or focus again this page); the function is whenVisChg(), see the comments in code.

Script code - click to select it

//JS code from:
// Defines a handler for page visibility changes
var vis_chg = (function(){
  var stateKey, eventKey, keys = {
    hidden: 'visibilitychange',
    webkitHidden: 'webkitvisibilitychange',
    mozHidden: 'mozvisibilitychange',
    msHidden: 'msvisibilitychange'
  for(stateKey in keys){
    if(stateKey in document){
      eventKey = keys[stateKey];
  return function(c){
      document.addEventListener(eventKey, c);
      //document.addEventListener('focus', c); //for when focus again this page
    return !document[stateKey];

// Gives the initial state
var page_vstate = vis_chg() ?'visible' :'not-visible';

  var re_vchg = vis_chg(); //FALSE=leaves the page; TRUE=re-enter in page
  console.log(new Date, 'vis_chg: ', re_vchg); //for debug in console
  page_vstate = re_vchg ?'visible' : whenVisChg();

//This function is executed when the page changes visibility state
function whenVisChg(){
  document.title ='not-visible';  //changes page title in browser

  //HERE you can set your code
  alert('page visibility state changed');

  return 'not-visible';
- To test the script, click on , or just open a new tab /window in your browser. The Title of this page in browser will be changed and an alert message box will be displayed on this page.

Daily Test with Code Example

Which tag is a block element?
<div> <img> <span>
<div>Web Programming and Development</div>
Which CSS code displays the text underlined?
font-style: italic; text-decoration: underline; font-weight: 500;
h2 {
  text-decoration: underline;
Click on the JavaScript function that can access other function after a specified time.
insertBefore() setTimeout() querySelector()
function someFunction() { alert(""); }
setTimeout("someFunction()", 2000);
Click on the instruction that returns the number of items of a multidimensional array in PHP.
count($array) count($array, 1) strlen()
$food = array("fruits" => array("banana", "apple"), "veggie" => array("collard", "pea"));
$nr_food = count($food, 1);
echo $nr_food;       // 6
Detect when page visibility state is changed

Last accessed pages

  1. Add, Change, and Remove Attributes with jQuery (23071)
  2. Get Attribute (ID, Class, Name, Title, Src) with jQuery (32104)
  3. Butterfly Kyodai (6922)
  4. Zuma Games (9008)
  5. Mahjong Games (7595)

Top accessed pages

  1. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (47880)
  2. Read Excel file data in PHP - PhpExcelReader (35991)
  3. PHP-MySQL free course, online tutorials PHP MySQL code (35605)
  4. Get Attribute (ID, Class, Name, Title, Src) with jQuery (32104)
  5. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (29375)