start animation when tab/page active - javascript

I have simple question about start animation of page when tab or page is active. I mean when user open the page but start browering another website until our website loads. then he click over our website tab and then animation loads. I've seen this on many websites but never know what's the trick to do this.
for the demo go to: http://swiftideas.net/
open website and go to another page, when website fully loaded, click on swiftideas website. You will see that a fade effect saying "HELLO. WE ARE SWIFT IDEAS" and Menu Also!
But it starts when you come over the page. pretty intelligent! Any clue how to achrive this?
I hope you people also like this!

From: How to tell if browser/tab is active
You would use the focus and blur events of the window:
var interval_id;
$(window).focus(function() {
if (!interval_id)
interval_id = setInterval(hard_work, 1000);
});
$(window).blur(function() {
clearInterval(interval_id);
interval_id = 0;
});
To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// do work
break;
case "focus":
// do work
break;
}
}
$(this).data("prevType", e.type);
})

Related

How to handle desktop notification in multiple tabs [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a way to detect if a browser window is not currently active?
I have a function that is called every second that I only want to run if the current page is in the foreground, i.e. the user hasn't minimized the browser or switched to another tab. It serves no purpose if the user isn't looking at it and is potentially CPU-intensive, so I don't want to just waste cycles in the background.
Does anyone know how to tell this in JavaScript?
Note: I use jQuery, so if your answer uses that, that's fine :).
In addition to Richard Simões answer you can also use the Page Visibility API.
if (!document.hidden) {
// do what you need
}
This specification defines a means for site developers to
programmatically determine the current visibility state of the page in
order to develop power and CPU efficient web applications.
Learn more (2019 update)
All modern browsers are supporting document.hidden
http://davidwalsh.name/page-visibility
https://developers.google.com/chrome/whitepapers/pagevisibility
Example pausing a video when window/tab is hidden https://web.archive.org/web/20170609212707/http://www.samdutton.com/pageVisibility/
You would use the focus and blur events of the window:
var interval_id;
$(window).focus(function() {
if (!interval_id)
interval_id = setInterval(hard_work, 1000);
});
$(window).blur(function() {
clearInterval(interval_id);
interval_id = 0;
});
To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// do work
break;
case "focus":
// do work
break;
}
}
$(this).data("prevType", e.type);
})
Click to view Example Code Showing it working (JSFiddle)
I would try to set a flag on the window.onfocus and window.onblur events.
The following snippet has been tested on Firefox, Safari and Chrome, open the console and move between tabs back and forth:
var isTabActive;
window.onfocus = function () {
isTabActive = true;
};
window.onblur = function () {
isTabActive = false;
};
// test
setInterval(function () {
console.log(window.isTabActive ? 'active' : 'inactive');
}, 1000);
Try it out here.
Using jQuery:
$(function() {
window.isActive = true;
$(window).focus(function() { this.isActive = true; });
$(window).blur(function() { this.isActive = false; });
showIsActive();
});
function showIsActive()
{
console.log(window.isActive)
window.setTimeout("showIsActive()", 2000);
}
function doWork()
{
if (window.isActive) { /* do CPU-intensive stuff */}
}
All of the examples here (with the exception of rockacola's) require that the user physically click on the window to define focus. This isn't ideal, so .hover() is the better choice:
$(window).hover(function(event) {
if (event.fromElement) {
console.log("inactive");
} else {
console.log("active");
}
});
This'll tell you when the user has their mouse on the screen, though it still won't tell you if it's in the foreground with the user's mouse elsewhere.
If you are trying to do something similar to the Google search page when open in Chrome, (where certain events are triggered when you 'focus' on the page), then the hover() event may help.
$(window).hover(function() {
// code here...
});

How to get javascript Timer to stop when not viewing tab/window

I am running a page with a timer that I'm using to run in a iframe of a page so that I know that someone was on there actually with window in focus paying attention to screen and if leave have the timer pause until back viewing the window or in focus.
I have 4 timer files: timer.css timer.js timer.php & timerb.js
I believe I would execute it in the following file and code, but that is where I am stuck as don't know what or where to add it for sure and no luck yet and why here asking so please take a look and let me know if you can help.
File: timer.js
function adTimer() {
timer++;
if(timer == fulltimer) {
var show="Click "+key;
$("#buttons").fadeIn();
$("#timer").html(show);
}
else {
setTimeout(adTimer, 1000);
}
$("#bar").width((timer/fulltimer)*200);
}
This could be enough for you:
$(window).blur(function(){
//your code for inactive
});
$(window).focus(function(){
//your code for active
});
or non jQuery solution (https://stackoverflow.com/a/1760283)
window.onblur = function () {
//your code for inactive
};
window.onfocus = function () {
//your code for active
};
if not try Page Visibility API (answer already here https://stackoverflow.com/a/1060034)
Just wondering why all that implementation if JQuery already provide a timeout. did you try to use set Timeout.
http://www.sitepoint.com/settimeout-example/

How to synchronize setTimeout and mobile.navigate using jQuery Mobile?

I'm creating a small quiz, mobile app using jQuery Mobile, and I'm displaying a 3 second GIF at certain points. Though, because it is shown many times, I don't want to bother the user each time, and if he/she clicks anywhere on the page it goes to the next page, but I also have set up a setTimeout, which waits for three seconds, meaning of the GIF to display completely and then moves to the next page. As you can see this makes a problem. If I click the GIF, it moves to the next page, and then if I again move to the other page, after three seconds are passed it sends me back to the previous page, due to the setTimeout. I have the following code:
EDIT :
$(document).on("pagechange", function(event, ui) {
var clicked = false;
// Here comes some if-else statements checking which page is currently active
else if ($.mobile.activePage[0].id == "correctGIF") {
correct++;
nextpage = hashtag.concat(page, 'Correct');
$('#correctGIF').append('<img src="images/Correct1.gif">');
$('#correctGIF').click(function() {
clicked = true;
$.mobile.navigate(nextpage);
alert("alert from click");
});
setTimeout(function() {
if (!clicked) {
$.mobile.navigate(nextpage);
alert("alert from timeout");
}
}, 3000);
}
So, I need to somehow synchronize it. If there is a click it should ignore the setTimeout part, and if there is no click it should wait for three seconds for the GIF to finish, meaning should activate the setTimeout part. Also please note that this GIF is displayed many times during the quiz, not just once. Any ideas about this?
Have you tried this approach:
$(document).ready(function () {
$('#correctGIF').off('click').on('click', function () {
alert('navigate from click');
console.log('navigate from click');
if (!$('#correctGIF').hasClass('clickedImageClass')) {
$('#correctGIF').addClass('clickedImageClass');
}
});
setTimeout(function () {
if (!$('#correctGIF').hasClass('clickedImageClass')) {
alert('navigate from timeout');
console.log('navigate from timeout');
}
}, 3000);
});
JsFiddle demo here: http://jsfiddle.net/e35pn/13/

disable address bar and back and forward button of browser

how can I disable or hide address bar and back and forward buttons in ie and firefox
i tried lots of links and solutions but non of them worked
for example for disabling back button:
<script type = "text/javascript" >
function changeHashOnLoad() {
window.location.href += "#";
setTimeout("changeHashAgain()", "50");
}
function changeHashAgain() {
window.location.href += "1";
}
var storedHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != storedHash) {
window.location.hash = storedHash;
}
}, 50);
but it seems that it goes to previous page then it returns
and i trid :
window.scrollTo(0, 0); // reset in case prev not scrolled
var nPageH = $(document).height();
var nViewH = window.outerHeight;
if (nViewH > nPageH) {
nViewH -= 250;
$('BODY').css('height', nViewH + 'px');
}
window.scrollTo(0, 1);
}
for disabling menu bar but it didnt work
what can i do
Instead of disabling the back button, try to make your page that supports users to going back. It will increase the usability of your application.
Even you can impliment it for the ajax activities also.
Don't think you can disable buttons on browser. I mean, otherwise, we'd seen it on spyware infected sites...
In terms of hiding them, I've seen banks use a full screen popup without those buttons (but hardware button on mouse or hitting backspace still works).
Not tested but you can bind to the window's hashchange event.
For example, in jQuery it very easy to do:
$(window).bind('hashchange', function(e)
{
e.stopImmediatePropagation();
e.stopPropagation();
e.preventDefault();
return false; // stop event
});
The result is that the back button not changes the page when an anchor is in the url. But i agree with the first answer also (it is not a real answer i think, it is an advice).
You can also override the last entry in window.history, so user can't go back.

How to detect when a tab is focused or not in Chrome with Javascript?

I need to know if the user is currently viewing a tab or not in Google Chrome. I tried to use the events blur and focus binded to the window, but only the blur seems to be working correctly.
window.addEventListener('focus', function() {
document.title = 'focused';
});
window.addEventListener('blur', function() {
document.title = 'not focused';
});
The focus event works weird, only sometimes. If I switch to another tab and back, focus event won't activate. But if I click on the address bar and then back on the page, it will. Or if I switch to another program and then back to Chrome it will activate if the tab is currently focused.
2015 update: The new HTML5 way with visibility API (taken from Blowsie's comment):
document.addEventListener('visibilitychange', function(){
document.title = document.hidden; // change tab text for demo
})
The code the original poster gives (in the question) now works, as of 2011:
window.addEventListener('focus', function() {
document.title = 'focused';
});
window.addEventListener('blur', function() {
document.title = 'not focused';
});
edit: As of a few months later in Chrome 14, this will still work, but the user must have interacted with the page by clicking anywhere in the window at least once. Merely scrolling and such is insufficient to make this work. Doing window.focus() does not make this work automatically either. If anyone knows of a workaround, please mention.
The selected answer for the question Is there a way to detect if a browser window is not currently active? should work. It utilizes the Page Visibility API drafted by the W3C on 2011-06-02.
It might work after all, i got curious and wrote this code:
...
setInterval ( updateSize, 500 );
function updateSize(){
if(window.outerHeight == window.innerHeight){
document.title = 'not focused';
} else {
document.title = 'focused';
}
document.getElementById("arthur").innerHTML = window.outerHeight + " - " + window.innerHeight;
}
...
<div id="arthur">
dent
</div>
This code does precisly what you want, but on an ugly way. The thing is, Chrome seems to ignore the title change from time to time (when switching to the tab and holding the mouse down for 1 sec seems to always create this effect).
You will get different values on your screen, yet your title won't change.
conclusion:
Whatever you are doing, don't trust the result when testing it!
For anyone who wants to swap page titles on blur and then go back to the original page title on focus:
// Swapping page titles on blur
var originalPageTitle = document.title;
window.addEventListener('blur', function(){
document.title = 'Don\'t forget to read this...';
});
window.addEventListener('focus', function(){
document.title = originalPageTitle;
});
I found that adding onblur= and onfocus= events to inline bypassed the issue:
This could work with JQuery
$(function() {
$(window).focus(function() {
console.log('Focus');
});
$(window).blur(function() {
console.log('Blur');
});
});
In chrome you can run a background script with a timeout of less than 1 second, and when the tab does not have focus chrome will only run it every second. Example;
This doesn't work in Firefox or Opera. Don't know about other browsers, but I doubt it works there too.
var currentDate = new Date();
var a = currentDate.getTime();
function test() {
var currentDate = new Date();
var b = currentDate.getTime();
var c = b - a;
if (c > 900) {
//Tab does not have focus.
} else {
//It does
}
a = b;
setTimeout("test()",800);
}
setTimeout("test()",1);

Categories