HTML - refresh page after inactivity - html

I am having a touch screen with some very basic html pages. But if there is no activity for maybe 5 minutes, it should reload the main page again.
So it is not just a refresh of the site, but a load of the main page if there is no activity
just a question Where does the script know which site is the main page ?. If someone goes to "site B" - it should after some minutes without any movement move back to "site A"

Here is plain JavaScript implementation, without any dependencies:
var inactivityTime = function () {
var timer;
window.onload = timerReset;
document.onkeypress = timerReset;
document.onmousemove = timerReset;
document.onmousedown = timerReset;
document.ontouchstart = timerReset;
document.onclick = timerReset;
document.onscroll = timerReset;
document.onkeypress = timerReset;
function timerElapsed() {
console.log("Timer elapsed");
location.reload();
};
function timerReset() {
console.log("Reseting timer");
clearTimeout(timer);
timer = setTimeout(timerElapsed, 5 * 60 * 1000); // 5 mins
}
};
You can adjust list of events to listen to achieve best performance.
Complete list of DOM events.

You would need to use JavaScript. There is a The jQuery idletimer plugin at
http://paulirish.com/2009/jquery-idletimer-plugin/
Example:
// idleTimer() takes an optional argument that defines the idle timeout
// timeout is in milliseconds; defaults to 30000
$.idleTimer(10000);
$(document).bind("idle.idleTimer", function(){
// function you want to fire when the user goes idle
});
$(document).bind("active.idleTimer", function(){
// function you want to fire when the user becomes active again
});
// pass the string 'destroy' to stop the timer
$.idleTimer('destroy');
Reference:
How to change a page location after inactivity of 5 mins

Assuming no activity means you do not get click, scroll and movement events. You need to listen to these events in the body element of your page and set a range that calls the page refresh method.
var timeOut = null;
var activityMade = function(){
clearInterval(timeOut); //first clears the interval
timeOut = setInterval(function(){ console.log("Page Refreshed"); }, 3000); //logs to the console at every 3 seconds of inactivity
}
var bindEvents = function(){
var body = document.getElementById("app");
// bind click move and scroll event to body
body.addEventListener('click', activityMade);
body.addEventListener('mousemove', activityMade);
body.addEventListener('scroll', activityMade);
activityMade(); // assume activivity has done at page init
}
bindEvents();
You can bind as may events as you wish to ajust it to your needs.
Here is an working example https://jsfiddle.net/fspayfqt/
Please note that for this to work perfectly the body element will cover the whole window of the navigator and this can be solved with css using fixed position with height and width of 100%

Related

Unable to scroll on website

On this website I am unable to scroll.
www.Batan.io
When I load the website for the first time the trackpad (mac) works fine but then the scroll function stops working. The sidebar works, I have changed the CSS position but to no avail.
Please will someone tell me why scrolling does not work on this website?
Thanks very much,
Thomas
$(function () {
$('body').bind('mousewheel', function (event) {
event.preventDefault();
var scrollTop = this.scrollTop;
this.scrollTop = (scrollTop + ((event.deltaY * event.deltaFactor) * -1));
//console.log(event.deltaY, event.deltaFactor, event.originalEvent.deltaMode, event.originalEvent.wheelDelta);
});
});
There are likely a few issues with this code:
Unless setup otherwise, theHTML element will be the scrollable element
You are attempthing to access a jQuery function on a vanilla javascriptthis
You are not actually executing that function to get the value
You are not calling the funciton to set the desired value
$(function() {
// Change 'body' to 'html'
$('html').bind('mousewheel', function(event) {
event.preventDefault();
var $window = $(this); // <--- Wrap the event target with a jQuery object
var scrollTop = $window.scrollTop(); // <--- Call this function to return the result (use parens)
/*
Otherwise the reference on this line is to a function, not a value,
and call the function (instead of setting a property)
*/
$window.scrollTop(scrollTop + ((event.deltaY * event.deltaFactor) * -1));
});
});

Form: Onload a script, wait 2 sec, then load next

I have a page that automatically gets the position, and fills it into a form.
</script>
<body onload="getLocation();">
Then i have to wait 2 sec, and push a button to convert position to real address.
<input id="submit" type="button" value="Reverse Geocode">
How can i trigg the button automatically or remove the button and have the trigging automatically-
With a time delay of 2 sec?
Code:
function getLocation(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);
}
else{
alert("Sorry, browser does not support geolocation!");
}
}
You can use the setTimeout() function to run a function after a defined number of milliseconds. In your case,
function getLocation(){
if(navigator.geolocation){
var options = {timeout:60000};
navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);
setTimeout(
function(){
document.getElementById("submit").click(); //Click the Button
},
2000 // 2000 milliseconds = 2 seconds
);
}
else{
alert("Sorry, browser does not support geolocation!");
}
}
The DOM click() method is used to virtually click the button with JavaScript.
You are looking for 'setTimeout' function:
setTimeout(function () {
// your code
}, 3000);

Clicking, pasting text and uploading files from extension

So I'm basically developing an automated click-paste-and-upload system for mutiple texts and files inside a google page.
This method helped me get the instances of objects that I'm looking for: buttons, textboxes, richtextboxes, etc.
Now I want to work with them.
So for example I know the id of a button , and the function subscribed to its click event. How do I trigger the click event from the extension ? I've tried injecting a script with the click event handler (discovered with DOM inspector) at "document_startup" but I don't get an error or anything else.
Here's the content script! The loggerhead function should have inserted the script but I don't think it did. What might be the reason for the blow code not giving anything?
// Runs a function for every added DOM element that matches a filter
// filter -- either function(DOM_node){/*...*/}, returns true or false
// OR a jQuery selector
// callback -- function(DOM_node){/*...*/}
function watchNodes(filter, callback){
observer = new MutationObserver( function (mutations) {
mutations.forEach( function (mutation){
if(typeof filter === "function"){
$(mutation.addedNodes).filter(
function(i){ return filter(this); }
).each(
function(i){ callback(this); }
);
} else {
$(mutation.addedNodes).filter(filter).each(
function(i){ callback(this); }
);
}
});
});
// For every added element, a mutation will be processed
// with mutation.taget == parent
// and mutation.addedNodes containing the added element
observer.observe(document, { subtree: true, childList: true });
}
function loggerhead(node) {
console.log("passhead");
//also inject jquery
var jqueryEl = document.createElement('script');
jqueryEl.setAttribute('src', chrome.extension.getURL('jquery-1.11.1.min.js'));
jqueryEl.setAttribute('type', 'text/javascript');
var scriptEl = document.createElement('script');
scriptEl.setAttribute('src', chrome.extension.getURL('script.js'));
scriptEl.setAttribute('type', 'text/javascript');
node.appendChild(jqueryEl);
node.appendChild(scriptEl);
}
watchNodes("head", loggerhead);
// method not working
//var gmailHead = jQuery("head", document).get(0);
script.js contains the function of subscribed to the click event of the button that I've managed to find through the DOM inspector:
function Cdb(b){return function(){if(Vbb()){return Ddb(b,this,arguments)}else{var a=Ddb(b,this,arguments);a!=null&&(a=a.val);return a}}}
You should try to call the existing click handler like
buttonElement.click()

count total clicks made by user on entire site and change background accordingly

how would I go about tracking the number of click a user make on a site, and change the background accordingly, so for example: when a user lands of the first page the background is a small object, then as the user explores the site, the background changes, according to how many links have been clicked through, this would then cycle round.
these are the ideas i have come up with:
track the incoming source on each page, and if source was from this site, then add 1 to a counter stored in cookie, retrieve cookie and display corresponding background.
or to cause click on link to add one to counter in cookie.
any other suggestions or ideas? or is this bad practice or a very bad idea?
ps re research i tried and failed to find anything useful
You can do that easily with jQuery:
EDIT with $.cookie usage:
var totalClicks = ($.cookie('totalClicks' !== null) ? $.cookie('totalClicks') : 0;
var clicksLimit = 10;
$.cookie('clicksLimit', clicksLimit); // just so that you do not have to re-declare this variable on the other page.
$('body').on('click', '*', function() {
totalClicks++;
if(totalClicks >= clicksLimit) {
alert('do something here...');
// precise to your request:
$('body').css('background-color', '#f00'); // will turn body background to "red"
}
$.cookie('totalClicks', totalClicks);
});
It can be done using simple javascript, using jQuery would increase load on the server:
var clicks = 0;
var limit = 10;
document.onclick = function() {
if(clicks == 1) document.body.style.backgroundColor = "#FFF";
if(clicks == 2) document.body.style.backgroundColor = "#EEE";
if(clicks == 3) document.body.style.backgroundColor = "#DDD";
if(clicks == 4) document.body.style.backgroundColor = "#CCC";
....
clicks++;
};
you can do this
// Get click amount from localStorage or use 0 if it doesn't exist
var clicks = localStorage['clicks'] || 0;
// Add the click className to the body first
document.body.className = 'style-' + clicks;
// Set a eventListener
document.addEventListener('click', function(){
// clicks + 1
clicks++;
// Add new class name
document.body.className = 'style-' + clicks;
}, false);
// When the window is about to be closed save the clicks in localStorage
window.onbeforeunload = function(){
localStorage['clicks'] = clicks;
};
here is a fiddle ignore the buttons and just look at the body tag in dev tools
Fiddle
you may have to do some cross browser work but it's the idea.
there is a polyfill for localStorage here https://gist.github.com/remy/350433
But--- if the browser doesn't support localStorage then this doesn't seem like a high priority feature for the site so the only thing that won't work it the state change on reload

Do not fire 'zoom_changed' event when calling fitBounds function on map

Is there a way to prevent the zoom_change event from being triggered if it occurs due to fitBounds() ?
I am having an issue where I need to do a search on the server from client when there is a zoom change to map but every time I call fitBounds() it causes zoom_change to trigger which causes the client to do another search on the server. I am only interested in zoom_change done by users and not programmatically using fitBounds.
When you do a fitBounds in your program, set a global flag. When the zoom_changed event fires, if the flag is set, clear it, otherwise send your request off to the server.
After many frustrating hours, here is my solution:
var tiles_listener = google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
var zoom_listener = google.maps.event.addListener(map, 'zoom_changed', function() {
reloadMarkers();
});
});
Note that I am calling addListenerOnce for tilesloaded to ensure that the zoome_changed listener is only added once, after the first fitBounds completes.
It's an old question, but it may be useful to others. I had the same problem, zoom_changed been triggered every time I called fitBounds() when adding several markers to a map. What I did was to add the listener to the map_changed event after the map was completely loaded, like this:
google.maps.event.addListener(map, 'tilesloaded', function() {
google.maps.event.addListener(map, 'zoom_changed', function() {
There is another way to do that by removing that that event. I think it would be much easier and cleaner than adding a global variable.
vm.map.events.bounds_changed = function() {
google.map.event.removeListener(zoom_changed);
}
Another way (forgotten to add that):
vm.map.events.bounds_changed = function() {
google.map.event.addEventListener(zoom_changed,function(mapper,eventName,args){});
}
In my app, I may fire off zoom change events programmatically, either via setZoom(), fitBounds(), or setOptions().
MAN = {};
MAN.globalMap = google.maps.Map(document.getElementById('map'));
I then route all programmatic calls to set the zoom through wrapper functions that flip a flag to false before they go on to set the zoom.
MAN.savedZoom = MAN.globalMap.getZoom();
MAN.saveZoomFlag = true;
// we want it to always be true, unless zoom was
// changed programatically.
MAN.setZoom = function setZoom(zoomLevel) {
console.log("won't save that I'm setting zoomLevel to " + zoomLevel);
this.saveZoomFlag = false;
MAN.globalMap.setZoom(zoomLevel);
};
MAN.fitBounds = function fitBounds(bounds) {
console.log("setting bounds, won't save zoomlevel.");
this.saveZoomFlag = false;
MAN.globalMap.fitBounds(bounds);
};
MAN.setOptions = function setOptions(options) {
console.log("setting options, won't save zoomlevel.");
this.saveZoomFlag = false;
MAN.globalMap.setOptions(options);
};
I then declare a listeners. At first I was declaring only the first, and was puzzled that it wasn't working:
google.maps.event.addListener(
MAN.globalMap,
'zoom_changed',
function zoom_changed_listener() {
console.log(
"zoom changed to " +
MAN.globalMap.getZoom() + "; " +
(MAN.saveZoomFlag ? "saving." : "not saving.")
);
if (MAN.saveZoomFlag) {
console.trace("saving");
MAN.savedZoom = MAN.globalMap.getZoom();
}
MAN.saveZoomFlag = true;
}
);
you may also find the idle event helpful, however, if you're just trying to avoid the initial set. See more about the maps events here: https://developers.google.com/maps/documentation/javascript/events
I suppose this should be simple. Have a variable say
var z = map.getZoom(); //scope this variable appropriately(somewhere before you call the fitbounds()
and then after the map.fitbounds() immediately do
map.setZoom(z); //this automatically changes the zoom level back to the previous level