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

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/

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...
});

Disable browser back action using jquery

I am developing an online testing app and it is required that during the test, users cannot be allowed to refresh page neither go back until the test is ended. I have successfully been able to disable refresh action in jquery through all means possible (to the best of my knowledge) using the following code:
$(window).bind({
beforeunload: function(ev) {
ev.preventDefault();
},
unload: function(ev) {
ev.preventDefault();
}
});
But I have been having troubles disabling the back action on all browsers, the best solution I got on SO conflicts with the code I have above, it is given below:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
//alert("Reloaded");
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload forthis.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
}
The solution above suits my purpose in disabling the back button but conflicts with the page refresh prevention handler above.
I am out of ideas on what to do and I have also searched a long time for a solution to this but found none yet. Any help would be greatly appreciated, even if it takes a totally different approach to solving the problem, I wouldn't mind at all.
Thanks everyone
UPDATE
I never realized that doing things this way breaks a lot of ethical rules, anyway, I've thought about it and figured out something else to do when if the page is refreshed or back button pressed (either using keyboard or the browser controls). I want to redirect to a url which will end the current exam session. I believe that's possible, hence I think the solution I seek is to get the best way to achieve this. Redirecting to another url if back button or refresh button is pressed (both using the browser controls and the keyboard).
I have tried many options but none worked except this-
//Diable Browser back in all Browsers
if (history.pushState != undefined) {
history.pushState(null, null, location.href);
}
history.back();
history.forward();
window.onpopstate = function () {
history.go(1);
};
With regards to the update I posted in my question, I have been able to solve my problem. Here's what I did (just modifying my existing code a little and removing the window.onload listener I had initially):
$(window).bind({
beforeunload: function(ev) {
window.location.replace("my_url_goes_in_here");
},
unload: function(ev) {
window.location.replace("my_url_goes_in_here");
}
});
This construct works for both page refresh and back actions done in anyway (either using keyboard or browser controls for the any of them).
However, I've not yet tested in any other browser other than firefox 47.0, but I'm glad it's working for now all the same.
Thanks for all your comments, they were extremely helpful
Using javascript if you have two pages page1 and page2 and (page1 redirect to page2) and you want to restrict the user from getting back to page1, just put this code at page1.
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
function disableBack() {
window.history.forward()
}
window.onload = disableBack();
window.onpageshow = function (evt) {
if (evt.persisted)
disableBack()
}
});
</script>

Qualtrics: Pressing enter key to emulate continue button

I'm very new to JavaScript, and I'm currently trying to add a custom code to my Qualtrics survey that makes it so pressing the enter key continues the survey. I have a code that should be working; however, I'm getting an "Unexpected token )" error.
Here is the code:
Qualtrics.SurveyEngine.addOnload(function()
{
document.addEventListener("keydown", function(e) {
if (e.keyCode === 13) {
function(){
that.clickNextButton();
}
}
}
});
the "clickNextButton" function was found in the Qualtrics API document and is supposed to emulate the next button click. The function is clickNextButton(), but the example provided has the code as that.clickNextButton().
The example they use is below:
//Hides the next button and displays the question
//for 5 seconds before moving to the next page
this.hideNextButton();
var that = this;
(function(){that.clickNextButton();}).delay(5);
I don't need the hiding button function or the delay, but just wanted to include an example of how it is used.
Any help is much appreciated, thanks in advance!
Here is a simplified version that works (updated to hide NextButton):
Qualtrics.SurveyEngine.addOnload(function() {
$('NextButton').hide();
document.on("keydown", function(e) {
if (e.keyCode === 13) $('NextButton').click();
});
});
It depends on the scope, or specifically where the function clickNextButton resides.
If you don't bother with the timeout you should be able to just remove the word 'that' from your Qualtrics.SurveyEngine function and it should work fine.
It's possible the function is not available in your current scope. So if removing 'that' doesn't work. Put it back in and put var that = this; in the line before your function call. It's far from a tidy way to do things at all but it may fix things for you.
Worth reading this.
http://www.w3schools.com/js/js_scope.asp
Didn't Meatloaf say something like... I'd do anything for scope.... but I don't do THAT?
As said in my comment...See if it solves your error
Qualtrics.SurveyEngine.addOnload(function()
{
document.addEventListener("keydown", function(e) {
if (e.keyCode === 13) {
function(){
that.clickNextButton();
}
}
} ); // here was a missing bracket here
});
So I have a video embedded in a question and I needed to disable to Next button for 15 seconds in that way I would know that autoplay video was watched.
And this worked for me so well:
Qualtrics.SurveyEngine.addOnload(function()
{
//Hides the next button and displays the question
//for 15 seconds before moving to the next page
this.disableNextButton();
var that = this;
(function(){that.enableNextButton();}).delay(15);
});
You can change the (15) seconds to any number, the Next Button will be activated and ready to be clicked next, but not automatically send you to next page.

Starting, stopping & refreshing timer javascript

I have a little fiddle here where I'm starting/stopping/resetting a javascript timer.
The functionality needs to be a timer runs on a page. When the timer is up, it sends a message, then restarts. The stop button will stop the timer completely.
The fiddle above has the functionality I just described, however I feel like I'm not doing this correctly. Is setTimeout the correct way to create this timer? Should I use setInterval instead?
Secondly, my reset code looks like :
var onReset = function() {
clearTimeout(timerHandle);
onStart();
};
Is there a more elegant way to reset a timer in javascript?
Thanks.
The only improvement I can offer is for you to put it all in an encapsulated object, ask if you want an example. Or if you want to keep the structure you've got then change your onStart function to this to remove a bit of un-needed code.
var onStart = function() {
timerHandle = setInterval(function() {
$("#console").append("timer fired.. <br />");
}, 2000);
};
Fiddle here http://jsfiddle.net/qx6CM/

Detect the browser tab switching/ browser minimising using javascript

I am trying to code my own versions of popular games such as minesweeper, snake etc using JavaScript. Some of the games require timer, so I wonder is it possible to detect whether user switched to another tab or minimized the browser so I can put the game on pause mode? Thanks for any help provided!
You could set a var when the window catches the onblur event.
<script>
var has_blurred = 0;
function meep()
{
has_blurred = 1;
game.pause();
}
window.onblur=meep;
</script>
EDIT adding onfocus
Then later on in the same window/tab, you can handle if your window/tab has ever blurred with an onfocus handler.
<script>
function handleFocus()
{
if( has_blurred )
game.unpause();
has_blurred = 0; // reset has_blurred state
}
window.onfocus=handleFocus;
</script>
You can do with this code
$(document).ready(function(){
$([window, document]).focusin(function(){
//Your logic when the page gets active
}).focusout(function(){
//Your logic when the page gets inactive
});
});

Categories