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

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

Related

chrome ext many loads on update page

In app use content script for all pages, and send message to active page on complete loaded page, but I have many calls of script sometimes 2 and more:
You can see that here
Code implimentation:
chrome.tabs.onCreated.addListener(function (tabs) {
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if(changeInfo.status === "complete") {
let tabid = tab.id;
console.log("Site is valid: url -> " + tab.url)
chrome.tabs.executeScript(tab.id, {
file: '/injections/mobile.bet365.com.js',
});
console.log(tab);
setTimeout(function () {
console.log("timeout was set")
chrome.tabs.query({}, function (tabs) {
let countOpenedTabsFrom = tabs.length;
let opener = 1;
// на целевой вкладке
chrome.tabs.sendMessage(tabid, {
message: "start_app",
opener: opener,
queuenumber: countOpenedTabsFrom
}, function (response) {
console.log(response);
});
});
}, 500);
}
And executed script have many queries too.
Why is this happen?
Every time onCreated event fires, you're adding a new onUpdated listener.
When, after that, onUpdated event fires, all of them are executed, leading to the behavior you're seeing.
You either need to de-register the handlers when they are done, or register the handler only once. See chrome.events docs (which describe common points of all event objects in other APIs) for ideas on how to implement that.
Note that the code inside chrome.tabs.onCreated listener does not use the tabs parameter at all, so it's not clear why do you even need to listen to onCreated.

Ng-Show is not working properly

$scope.stay = function() {
alert("Inside Keep me In")
$scope.timed = false;
$scope.isLogStatus = true;
}
$scope.displayAlert = function() {
$scope.timed = true;
alert("inside display")
}
function idleTimer() {
var t;
$window.onmousemove = resetTimer; // catches mouse movements
$window.onmousedown = resetTimer; // catches mouse movements
$window.onclick = resetTimer; // catches mouse clicks
$window.onscroll = resetTimer;
//window.reload=$scope.stay(); // catches scrolling
// window.onkeypress = resetTimer; //catches keyboard actions
function logout() {
//Adapt to actual logout script
$scope.displayAlert();
alert('insinde logout');
// delete $window.localStorage.user;
// location.href="/";
}
function reload() {
$window.location = self.location.href; //Reloads the current page
}
function resetTimer() {
alert("timer reset")
clearTimeout(t);
// t = setTimeout(logout, 600000); // time is in milliseconds (1000 is 1 second)
$timeout(function() {
alert("timout triggered");
$scope.displayAlert();
}, 9000); // time is in milliseconds (1000 is 1 second)
}
}
idleTimer();
I am using above html and in default if I keep
$scope.timed=true;
it's working
and when I click logged in I am doing
$scope.timed=false;
and again if time is more than 10 minutes I am doing
$scope.timed=true;
(which is not triggering ng-show)
then show is not working
this is controller what is happening
$scope.stay = function() {
alert("Inside Keep me In")
$scope.timed = false;
$scope.isLogStatus = true;
}
$scope.displayAlert = function() {
$scope.timed = true;
alert("inside display")
}
function idleTimer() {
var t;
window.onmousemove = resetTimer; // catches mouse movements
window.onmousedown = resetTimer; // catches mouse movements
window.onclick = resetTimer; // catches mouse clicks
window.onscroll = resetTimer;
//window.reload=$scope.stay(); // catches scrolling
// window.onkeypress = resetTimer; //catches keyboard actions
function logout() {
//Adapt to actual logout script
$scope.displayAlert();
alert('insinde logout');
// delete $window.localStorage.user;
// location.href="/";
}
function reload() {
window.location = self.location.href; //Reloads the current page
}
function resetTimer() {
// alert("timer reset")
clearTimeout(t);
// t = setTimeout(logout, 600000); // time is in milliseconds (1000 is 1 second)
t = setTimeout(logout, 9000); // time is in milliseconds (1000 is 1 second)
}
}
idleTimer();
// Get the topbar menu
$scope.menu = Menus.getMenu('topbar');
The problem is with the way you are calling logout function. You are calling it via outside the angular framework which means that angular will not run the digest cycle and hence any change in scope will not be reflected to the view.
To verify, you can wrap the code in logout function with $timeout. Please do not forget to add it in the dependencies.
$timeout(function(){
$scope.displayAlert();
});
Ideally, you should use angular wrappers e.g. $window for window and $timeout for setTimeout. By doing so angular, automatically, watches for the change and run digest cycle accordingly.

HTML - refresh page after inactivity

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%

How to preload images on refresh?

I have a code, which gets refreshed from mysql database on a button click.
From the mysql I get links of images on refresh, but I never know, hat links and how many.
I have a "loading" circle which spins until the page is loaded, but it is shown only, until the code is loaded, which is not very long. After that I see small empty squares on my page as placeholders, until the real images show up.
Does anybody have an idea, how to show the spinning circle untill all images are loaded?
I tried some javascript examples found on the net with building arrays of links, but I was not able to integrate them into my code, because the construction of the codes are very different and I obviously am not a pro.
So here is my code (I simplified it for now):
$(document).ready(function() {
function refresh(free){
$("#loadingfree").show();
if (free) datum = datum + free;
var url = "listfree.php?date=" + datum;
$.getJSON(url,function(data) {
var div_data = '';
$.each(data, function(i,data) {
div_data += "<div class='iconsfree'><a href='"+data.title+"-"+data.appID+"' title='"+data.title+"'><img src='"+data.icon+"'></img></a></div>";
});
$("#loadingfree").hide();
$("#app-wrapper-free").html(div_data);
});
}
$(document).on('click', '#prevbuttonfree', function(e){
e.preventDefault();
$("#app-wrapper-free").empty();
refresh(-1);
});
$(document).on('click', '#nextbuttonfree', function(e){
e.preventDefault();
$("#app-wrapper-free").empty();
refresh(+1);
});
// call the method when page is opened:
refresh(0);
});
If you want the spinner to continue showing until the images are loaded, you should use the load eventListener to make that happen.
So let's say you have your code that has the spinner while it makes the request to the server.
//just an example
$('button').click(function(){
//call server
$.ajax();
//show spinner
$('.spinner').show();
});
Now we will tell the spinner to stay showing until the images are done loading.
$('img').on('load',function(){
//Not sure what your spinner is called
$('.spinner').hide();
});
I ended up with this.
It just shows the content a bit later. It's a fake preloader.
<script type="text/javascript">
var datum = 0;
$(document).ready(function() {
function refresh(free){
if (free) datum = datum + free;
var url = "listfree.php?date=" + datum;
$.getJSON(url,function(data) {
var div_data = '';
$.each(data, function(i,data) {
if ($("#date_free").html() == '');
div_data += "<div class='iconsfree'><a href='"+data.title+"-"+data.appID+"' title='"+data.title+"'><img src='"+data.icon+"'></img></a></div>";
});
$("#loadingfree").show();
$(div_data).hide()
.appendTo("#app-wrapper-free")
setTimeout( function() {
$("#app-wrapper-free").children().show()
$("#loadingfree").hide()
}, 3000 );
});
}
$(document).on('click', '#prevbuttonfree', function(e){
e.preventDefault();
$("#app-wrapper-free").empty();
refresh(-1);
});
$(document).on('click', '#nextbuttonfree', function(e){
e.preventDefault();
$("#app-wrapper-free").empty();
refresh(+1);
});
// call the method when page is opened:
refresh(0);
});
</script>

Repeat jQuery JSON request until condition is met

I am trying to repeat a JSON request in jQuery to check the status of a video encoding job until it is completed. "Processing" would be displayed until the job is finished, at which point the video will be displayed.
Would a loop, checking every x seconds to see if "status" equals "finished," be the best solution for this? If so, how would I break free from this loop when the job is finished?
The JSON response while the job is in progress will be nothing more than "processing," when it is finished it will contain things such as the job ID, width, and height.
Any help would be appreciated, thanks!
UPDATE
Here's my final solution thanks to Felix:
var checkStatus = function() {
$.getJSON('json-data.php', function(data) {
if (data.status != 'finished') {
setTimeout(checkStatus, 2000);
} else {
//Sample code to run when finished
$("#statusText").text("Job Complete");
$("#dimensions").text(data.width + 'x' + data.height);
}
});
};
checkStatus();
A loop won't work as the Ajax request is asynchronous.
One way would be to make same kind of recursive call and trigger the Ajax function again from the success callback (maybe after some timeout), if the condition is not met.
Something like (pseudo code):
function check_condition() {
$.getJSON(<url>, function(result) {
if(!result.finished) {
setTimeout(check_condition, 2000);
}
// do something else
}
}
var checkStatusInterval = 30 * 10000; // 30 seconds
var checkStatusFunc = function(){
$.getJSON('getMovieStatus', function(data){
if (data.Incompleted){ // or however you check
checkStatusTimer = setTimeout(checkStatusFunc, checkStatusInterval);
}
});
};
var checkStatusTimer = setTimeout(checkStatusFunc,checkStatusInterval );
To stop:
<input type="button" id="stopchecking" value="Stop Checking..." />
$('#stopchecking').click(function(e){
clearTimeout(checkStatusTimer);
});