change image according to world time zones? - javascript

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>

Related

Auto-click a button only only on first page load

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

Sending alert at certain time using javacript

I've success set single time to send alert. But I have problem to set multiple time. How set multiple time to send alert?
Example: I have to send alert at 14:05, 17: 35 and 19:12
<script type="text/javascript">
var alarmDate = new Date();
alarmDate.setHours(21);
alarmDate.setMinutes(47);
// set day, month, year, etc.
function setAlarm(){
var currentDate = new Date();
if (currentDate.getHours() == alarmDate.getHours() &&
currentDate.getMinutes() == alarmDate.getMinutes()
/* compare other fields at your convenience */ ) {
alert('Alarm triggered at ' + currentDate);
// better use something better than alert for that?
}
}
setInterval(setAlarm,1000)
</script>
Use setTimeout instead. There is no reason to call a piece of code to cehck what time it is every single second. Just wait until the time when you want to execute something.
// Set your alarm date to whatever you require
var alarmDate = new Date();
alarmDate.setSeconds(alarmDate.getSeconds() + 5);
setAlarm(alarmDate, function(){
alert('Alarm triggered at ' + new Date());
});
var alarmDate2 = new Date();
alarmDate2.setSeconds(alarmDate2.getSeconds() + 10);
setAlarm(alarmDate2, function(){
alert('Alarm triggered at ' + new Date());
});
function setAlarm(date, callback){
// How much time from now until the alarmDate
var timeUntilAlarm = date - new Date();
// Wait until the alarm date, then do stuff.
setTimeout(callback, timeUntilAlarm);
}

wavesurfer get elapsed time in real time

I'm using katspaugh's waveSurfer library for playing sound files.
I wrote code to show 'elapsed time / total time' in this way.
waveSurfer.on('play', function() {
$scope.getCurrentDuration();
});
$scope.getCurrentDuration() is a function to transform floating-type variable to string-type variable, like below:
$scope.getDuration = function() {
if ($scope.waveSurferReady) {
var time = waveSurfer.getDuration(); // get duration(float) in second
var minute = Math.floor(time / 60); // get minute(integer) from time
var tmp = Math.round(time - (minute * 60)); // get second(integer) from time
var second = (tmp < 10 ? '0' : '') + tmp; // make two-figured integer if less than 10
return String(minute + ':' + second); // combine minute and second in string
}
else {
return 'not ready yet'; // waveSurfer is not ready yet
}
};
But the problem is,
in this part:
waveSurfer.on('play', function() ...)
the callback function execute only once.
I expect the callback function called periodically, but it executes only once, so as the result, elapsed time is shown only at the start time.
How can I solve this?
Looking into the source, I've found the audioprocess event paired with html5 timeupdate event.
Try it out.
waveSurfer.on('audioprocess', function() {
// do stuff here
});

How would I make a Javascript timer that goes off once a day

What I would like is a timer in Javascript that goes off once a day at 2:00AM and when the timer went off there would be a alert. I'm just not sure how to do that.
P.S. I'm terrible at Javascript so if you could could you leave the whole script not just what to do :)
This should work.
function alarm() {
alert('my alert message');
setAlarm();
}
function setAlarm() {
var date = new Date(Date.now());
var alarmTime = new Date(date.getYear(), date.getMonth(), date.getDate(), 2);
if (date.getHours() >= 2) {
alarmTime.setDate(date.getDate() + 1);
}
setTimeout(alarm, alarmTime.valueOf() - Date.now());
}
setAlarm();
For a javascript web page to put up a prompt at a particular time in the future, you will have to leave a browser running with that page being displayed. Javascript from web pages in a browser only runs in pages that are currently open in the browser. If that's really what you want to do, then you can do so like this:
// make it so this code executes when your web page first runs
// you can put this right before the </body> tag
<script>
function scheduleAlert(msg, hr) {
// calc time remaining until the next 2am
// get current time
var now = new Date();
// create time at the desired hr
var then = new Date(now);
then.setHours(hr);
then.setMinutes(0);
then.setSeconds(0);
then.setMilliseconds(0);
// correct for time after the hr where we need to go to next day
if (now.getHours() >= hr) {
then = new Date(then.getTime() + (24 * 3600 * 1000)); // add one day
}
// set timer to fire the amount of time until the hr
setTimeout(function() {
alert(msg);
// set it again for the next day
scheduleAlert(msg, hr);
}, then - now);
}
// schedule the first one
scheduleAlert("It's 2am.", 2);
</script>

Facebook server time in javascript

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.

Categories

Resources