On my website I've got a button which is clicked automatically by js with the loading of the website.
window.onload=function(){
document.getElementById("myBtn").click();
};
The thing I don't know how to code is that I want the button only to be auto clicked at the first visit of the page or only once an hour...
Is there a way to do it without using jquery?
It took some time, but I think something like this will work for you. Let me know if you face any problem with this.
// Initialize an object
let obj = {};
// Trigger when DOM loads
window.addEventListener('DOMContentLoaded', () => {
// Get current Date in UNIX
let currentDate = Date.now();
// An hour in UNIX
const hour = 3600000;
// The date to reclick
let reclickDate = currentDate + hour;
// If already clicked
if (localStorage.getItem('clickData')){
// Parse the JSON object from localStorage
let data = JSON.parse(localStorage.getItem('clickData'));
// The Date to Reclick
reclickDate = Date(parseInt(data.clickTime)+hour);
}
// Otherwise click now and set object JSON
else {
document.getElementById("myBtn").click();
obj.clickTime = Date.now();
localStorage.setItem('clickData', JSON.stringify(obj));
}
// Recursive Function
checkForClick(currentDate, reclickDate);
});
const checkForClick = (currentDate, reclickDate) => {
setTimeout(() => {
// If 1 hour passed
if (currentDate > reclickDate){
// Reclick
document.getElementById("myBtn").click();
// Set localStorage new data
obj.clickTime = Date.now();
localStorage.setItem('clickData', JSON.stringify(obj));
// Break function
return;
}
// Otherwise recall the function
checkForClick(currentDate+1000, reclickDate);
}, 1000);
}
Try this below code using document ready function in jQuery:
$(document).ready(function(){
$("#myBtn").trigger('click');
});
Related
I am building a Chrome Extension and I am letting the user choose a Time when they are usually turning the PC off.
If this time has passed, I want a value to be reset back to 0 and a new Date be created.
What I did
I created a function that takes a parament of a Dare ISO String, which will then be converted into a Date Object. Inside that function I am comparing between now and the end time, and if the end time is smaller or equal to now, it means the time has passed and the value should be reset. But it's not doing anything.
I call the function inside my storage.sync.get method and inside my storage.onChanged method, so I always have the correct time to work with. But that does not seem to do it.
Here's the code:
Background.js
chrome.storage.onChanged.addListener((changes, namespace) => {
if ("reset" in changes) {
const reset = changes.reset.newValue;
console.log(reset);
checkResetTimer(reset);
}
});
chrome.storage.sync.get(["reset", "amount"], (obj) => {
const reset = obj.reset;
console.log(reset);
checkResetTimer(reset);
});
function checkResetTimer(isoTime) {
const resetDate = new Date(isoTime);
const now = new Date();
if (resetDate <= now) {
chrome.storage.sync.set({ drank: 0 }, () => {
console.log("drank has been set.");
});
}
}
The time value I get from the popup, it's an input.
I am at a loss right now. I don't know how to properly have a reset timer.
You can view my whole code in this Repository: https://github.com/Braweria/TakeAGulp
I feel the problem is, that it checks only once, but it needs to check the time consistently.
A crude approach to the problem can be the following:
Background.js
// rest of your code
const resetInterval = setInterval(() => {
chrome.storage.sync.get(["reset", "amount"], (obj) => {
const reset = obj.reset;
const resetTime = new Date(reset);
const now = new Date();
if(resetTime < now) {
// past your reset time; reset the value here
// maybe clear the interval too to stop the checking
clearInterval(resetInterval);
}
});
}, 1000 * 60); // check every minute
Essentially you have to check the value of the reset timer at a given interval to make sure whether that timer has expired.
While trying to find the time spent for a user on a page, using onbeforeunload() function where i can record the current time and pass it as custom attribute to newrelic event. Tried below with no result.
window.onbeforeunload = function(event) {
doSomething();
//event.returnValue = "Is this working";
};
function doSomething(){
//const t = new Date();
//const ctime = t.getTime();
//Test
newrelic.setCustomAttribute('ctime', "sal");
}
No data being captured in newrelic event.
I have a jQuery datatable that immediately loads ON READY. After that, the datatable is reloaded every 30 seconds. This feature is functioning properly.
I have added a search feature that automatically reloads the datatable with new search results. This part is also functioning properly.
The problem I am experiencing is when I am using the search feature, and the new search results are returned. After 30 seconds, the new results are cleared and the datatable reloads with all of the original records.
Here is what I am currently attempting:
$(document).ready(function()
{
var searchCriteria = "";
displayBookings(searchCriteria);
var idle = 0;
var idleInterval = setInterval(timer, 30000);
$(this).mousemove(function(e){idle = 0;});
$(this).keypress(function(e){idle = 0;});
function timer()
{
idle = idle + 1;
if(idle > 2)
{
displayBookings(searchCriteria);
console.log('table reloaded');
}
}
$('#searchPending').on('click', function()
{
var isPending = 'Y';
var searchCriteria = {
isPending: isPending
};
displayBookings(searchCriteria);
});
});
The function displayBookings() takes searchCriteria. If searchCriteria is blank, then a basic query is fired. Obviously is searchCriteria contains parameters, then the same query is fired with a WHERE clause attached. I did not disclose the code for displayBookings().
All I need to do is stop the 30 second interval if the #searchPending button is clicked.
Clear the interval so it will stop loading.
clearInterval(idleInterval)
specifically in your code:
$('#searchPending').on('click', function()
{
clearInterval(idleInterval)
var isPending = 'Y';
var searchCriteria = {
isPending: isPending
};
displayBookings(searchCriteria);
});
Rather than start and stop the timer interval, since you'll run into a bit of a race condition, you can just have the "refresh" (your "timer" function) refresh using the latest search criteria. To do this, just pass the same object into your displayBookings function. E.g.
const search = { criteria: "" };
$(...).click(() => {
search.criteria = 'change it...';
displayBookings(search.criteria);
});
setInterval(() => displayBookings(search.criteria), 30000);
This way, if a refresh happens, it will use the latest search.criteria. You can achieve the same result with minimal change in your code by simply removing the var from the second searchCriteria. Currently, without removing the var, your outer criteria is being "shadowed" by your inner.
I alluded to debouncing1 in one of my comments. I misread the code and debouncing is not what you want. Instead, you want to only "refresh" if there hasn't been any user activity within some threshold. Here's an alternative from the approach you used:
let lastInteraction = 0;
function interact() {
lastInteraction = Date.now();
}
$(this).mousemove(interact);
$(this).keypress(interact);
Then in your refresh function:
if (Date.now() - lastInteraction > threshold) { ...
Implementing both the central criteria and revised idle check:
$(document).ready(function() {
const idle = {
threshold: 1000,
lastInteraction: 0,
interact() {
idle.lastInteraction = Date.now();
},
isIdle() {
return Date.now() - idle.lastInteraction > idle.threshold;
}
};
const search = { criteria: "" };
$(this).mousemove(idle.interact);
$(this).keypress(idle.interact);
setInterval(() => {
if (idle.isIdle()) {
displayBookings(search.criteria);
}
}, 30000);
$('#searchPending').on('click', () => {
search.criteria = { isPending: 'Y' };
displayBookings(search.criteria);
});
displayBookings(search.criteria);
});
1 The Wikipedia article linked to discusses debouncing with a keyboard. It's the same concept. You'd use debouncing on your displayBookings function if you plan on having it execute live as the user is typing. This would prevent too many HTTP requests from happening in a short duration of time.
I want to make a banner in html in which images changes according to the day time i.e. i want to display one image between 7pm to 6am and other image during other time. After searching the wen i found out a website which does the same thing. In this the image changes according to the time of the system but i want to change the picture according to the world time zone. For eg. i wanted the image to change according to the timezone of say, Japan.
Here is the JS code:
function pixTimeChange() {
var t=new Date();
var h = t.getHours();
var r1="obanner1.jpg";
var r2="poolside3.png";
var el=document.getElementById('myimage');
// See the time below. Note: The time is in 24 hour format.
// In the example here, "7" = 7 AM; "17" =5PM.
el.src = (h>=7 && h<16) ? r1 : r2;
}
// Multiple onload function created by: Simon Willison
// http://simonwillison.net/2004/May/26/addLoadEvent/
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
pixTimeChange();
});
I've limited knowledge of Javascript and jQuery and need help in this making changes in this script.
Sorry if this question is out of scope of SO.
Check out this question for getting the timezone.
Then with JQuery you can set the src parameter for your image, like this:
if (userIsInJapan) {
$("#YourImgID").attr("src", r1);
}else{
$("#YourImgID").attr("src", r2);
}
EDIT:
I found some more details on how to check the timezone in this thread
I made this little example to show you how to use it
<script>
function calcTime(city, offset) {
// create Date object for current location
var d = new Date();
// convert to msec
// subtract local time zone offset
// get UTC time in msec
var utc = d.getTime() - (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time for "+ city +" is "+ nd.toLocaleString();
}
// Refresh the timer every 250 milliseconds
setInterval(function(){
$("#timeLabel").text(calcTime('Japan', '+6'));
}, 250)
</script>
<label id="timeLabel"></label>
Im trying to show on my site changeable clock synchronized with facebook server.
The fb server time is available at:
https://api.facebook.com/method/fql.query?query=SELECT+now%28%29+FROM+link_stat+WHERE+url+%3D+%271.2%27&format=json
How to make it changeable every second without refreshing the page?
Assuming some non-written functions, it should look like that:
var requestBegin = Date.now();
getServertimeFromFacebook(function callback(fbTime) {
var requestEnd = Date.now();
var latency = (requestEnd - requestBegin) / 2;
var curDevicetime = Date.now(); // = requestEnd, of course
var difference = fbTime - latency - curDeviceTime;
function clock() {
var cur = Date.now();
var curFbTime = cur + difference;
show(curFbTime); // print, log, whatever
};
setInterval(clock, …); // you could use a self-adjusting clock
// by using a setTimeout for each tick
});
You could do
show = function(t) { console.log(new Date(t).toString()); };
getServertimeFromFacebook = function(cb) {
ajax("https://api.facebook.com/method/fql.query?query=SELECT+now%28%29+FROM+link_stat+WHERE+url+%3D+%271.2%27&format=json", function(responsetext) {
var obj = JSON.parse(responsetext);
var ts = obj[0].anon,
tms = ts * 1000;
cb(tms);
});
};
I wouldn't call the API every second.
Instead, I would get the Facebook server time only one time at the beginning. And then, I would increment my time value every second by looping using javascript :
setTimeout(function() { /* increment time */ }, 1000);
Bergi: [{"anon":1354654854}] is a unix time. Indeed, Facebook often (always?) deals with time using this representation.