I'm trying to get this code to change the page title based on array elements. But there is something wrong with this code. I need the page title show the entire array only when the browser tab is inactive. When the browser tab is active show the real page title. This is the code that I got so far
Here is a fiddle: https://jsfiddle.net/hgmvqasn/2/
/*
*
Title Change Plugin, adapted
*
*/
window.onload = function() {
var pageTitle = document.title;
var appeal = ["Hello! ♥","Welcome Back!", "Are you sure?"];
var blinkEvent = null;
document.addEventListener('visibilitychange', function(e){
var isPageActive = document.visibilityState;
console.log(isPageActive);
if (isPageActive == "hidden") {
blinkEvent;
} else {
document.title = pageTitle;
clearInterval(blinkEvent);
}
})
blinkEvent = setInterval(function() {
function blink(){
for (i = 0; i < appeal.length; i++){
document.title = appeal[i];
console.log(appeal[i]);
}
// To make instant page title change (no wait the interval)
document.title = appeal[1];
}
}, 1900);
};
The code above does not display all items in the array or displays them in wrong way. In addition the interval is not interrupted when the tab becomes active again.Can someone help me?
forloop is starting multiple timers, and they all run at about the same time. Each one replaces the title with a different one, and all you see is the change from the last one.i(wrapping around when it reaches the end) and show that title.blinkEventonly contains the last timer. SoclearInterval(blinkEvent)only stops one of the timers, not all of them.document.hiddenis obsolete. The property you want isvisibilityState, which can have valuesvisibleorhidden. See developer.mozilla.org/en-US/docs/Web/API/Document/…. Also see the note there about Safari using thepagehideevent instead ofvisibilitychange.