How can I find a random location based on the moment-timezone.js? I want to show a new location every time you refresh the page.
Current code:
<hero>
<div id="hover">
<h2>Present time</h2>
<div id="time"></div>
</div>
</hero>
<script>
(function clock() {
var now = moment().format('lll'); //local time
/*
I want many of these..
moment.tz("Europe/Berlin").format('lll');
*/
var time = document.getElementById('time');
time.innerHTML = now;
setInterval(clock, 1000);
})();
</script>
You can choose a random timezone from all available timezones:
const timezones = moment.tz.names();
const randTimezone = timezones[Math.floor(Math.random() * timezones.length)];
const now = moment.tz(randTimezone).format('lll');
document.write(randTimezone, '<br>', now);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
You can get a random timezone by picking off a random element from all timezones.
var all = moment.tz.names();
var randomTimeZone = all[Math.floor(Math.random()*all.length)];
// Use it in the code as
moment.tz(randomTimeZone).format('lll');
Related
This script using warp.js works great starting from the current date. I can't seem to figure out how to get it to work starting from a previous date like Jan 2nd, 1986?
warp.js
https://github.com/mattbradley/warpjs/blob/master/README.md
Thanks!
<body>
<script src="warp.js"></script>
<div id="container"></div>
<span id="info"></span><br>
<span id="time"></span>
<span id="time2"></span>
<script>
setInterval(function() {
//specify a start date here like Jan 2 1986
Date.warp.speed(3);
var now = new Date;
//new date put out the warped start date above?
var dateD = [now.getMonth() + 1, now.getDate(), now.getFullYear()];
var dateE = [now.getHours(), now.getMinutes(), now.getSeconds()];
var MDY = dateD.join("/");
var HMS = dateE.join(":");
time.innerHTML = (MDY);
time2.innerHTML = (HMS);
}, 1000);
</script>
</body>
</html>
I figured this out. You have to use the clock() function so set your custom date, and it will then warp from that custom date.
Date.warp.clock(customDate);
I'm writing a Chrome web application and am trying to load a clock onto it, but this is not working. The HTML & CSS files are showing up but not the JS, meaning that the application just looks like an empty box.
I would really appreciate your help - thank you very much!
Here is my popup.html file:
<!DOCTYPEhtml>
<link rel="stylesheet" type="text/css" href="popup.css">
<title>Your Personal Homepage</title>
<script src="popup.js"></script>
<script src="clock.js"></script>
</head>
<body>
<div id="clock" class="light">
<div class="display">
<div class="weekdays"></div>
<div class="ampm"></div>
<div class="alarm"></div>
<div class="digits"></div>
</div>
</div>
<!-- JavaScript Includes -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.0.0/moment.min.js"></script>
</body>
</html>
And here is my clock.js file:
$(function(){
// Cache some selectors
var clock = $('#clock'),
alarm = clock.find('.alarm'),
ampm = clock.find('.ampm');
// Map digits to their names (this will be an array)
var digit_to_name = 'zero one two three four five six seven eight nine'.split(' ');
// This object will hold the digit elements
var digits = {};
// Positions for the hours, minutes, and seconds
var positions = [
'h1', 'h2', ':', 'm1', 'm2', ':', 's1', 's2'
];
// Generate the digits with the needed markup,
// and add them to the clock
var digit_holder = clock.find('.digits');
$.each(positions, function(){
if(this == ':'){
digit_holder.append('<div class="dots">');
}
else{
var pos = $('<div>');
for(var i=1; i<8; i++){
pos.append('<span class="d' + i + '">');
}
// Set the digits as key:value pairs in the digits object
digits[this] = pos;
// Add the digit elements to the page
digit_holder.append(pos);
}
});
// Add the weekday names
var weekday_names = 'MON TUE WED THU FRI SAT SUN'.split(' '),
weekday_holder = clock.find('.weekdays');
$.each(weekday_names, function(){
weekday_holder.append('<span>' + this + '</span>');
});
var weekdays = clock.find('.weekdays span');
// Run a timer every second and update the clock
(function update_time(){
// Use moment.js to output the current time as a string
// hh is for the hours in 12-hour format,
// mm - minutes, ss-seconds (all with leading zeroes),
// d is for day of week and A is for AM/PM
var now = moment().format("hhmmssdA");
digits.h1.attr('class', digit_to_name[now[0]]);
digits.h2.attr('class', digit_to_name[now[1]]);
digits.m1.attr('class', digit_to_name[now[2]]);
digits.m2.attr('class', digit_to_name[now[3]]);
digits.s1.attr('class', digit_to_name[now[4]]);
digits.s2.attr('class', digit_to_name[now[5]]);
// The library returns Sunday as the first day of the week.
// Stupid, I know. Lets shift all the days one position down,
// and make Sunday last
var dow = now[6];
dow--;
// Sunday!
if(dow < 0){
// Make it last
dow = 6;
}
// Mark the active day of the week
weekdays.removeClass('active').eq(dow).addClass('active');
// Set the am/pm text:
ampm.text(now[7]+now[8]);
// Schedule this function to be run again in 1 sec
setTimeout(update_time, 1000);
})();
Is there any way to make this show up?
Thank you!
Your clock.js uses jQuery but is loaded before jQuery is loaded. Include it after jQuery instead.
Chrome extensions and apps obey a Content Security Policy.
This disallows external scripts, so you should download the external files and put them in the same folder as your other scripts.
I'm having an issue trying use local storage values to save a timer on a webpage, navigate to another page, then start the timer again from the values saved from clicking off the initial page.
I have the seconds to work but struggling with the minutes and hours, not sure what I'm doing wrong.
I can input the saved minutes and hours values into the formula, but since the formula dynamically updates every second it doesn't work correctly.
Any help on this would be really appreciated, thanks.
Here is the code:
var secondtime = localStorage.getItem("Seconds");
var minutetime = localStorage.getItem("Minutes");
var hourtime = localStorage.getItem("Minutes");
var sec = localStorage.getItem("Seconds");
setInterval( function(){
document.getElementById("text").innerHTML;
document.getElementById("seconds").innerHTML=pad(++sec%60);
document.getElementById("minutes").innerHTML=pad(parseInt(sec/60,10));
document.getElementById("hours").innerHTML=pad(parseInt(sec/6000,10));
}, 1000);
function SaveTime() {
localStorage.setItem("Seconds", $("#seconds").text())
localStorage.setItem("Minutes", $("#minutes").text())
localStorage.setItem("Hours", $("#hours").text())
}
$(document).ready(function(e) {
$("#seconds").text(secondtime);
$("#minutes").text(minutetime);
$("hours").text(hourtime);
<div class="Bottom_Bar">
<p class="c1" id="seconds_text"><span id="seconds">00</span></p>
<p class="c1" id="minutes_text"><span id="minutes">00</span></p>
<p class="c1" id="hours_text"><span id="hours">00</span></p>
<div class="Button">
<a href="NextPage.html"> onclick="SaveTime()</div>
First thing i'd like to bring to your notice is that you are trying to assign minuts to hourTime variable too take a look at you initialization
var hourtime = localStorage.getItem("Minutes");
And below is the simple code which store and retrieves time from local storage
Save Current Time |
Retrieve Saved Time
<div id="result"></div>
function SaveTime(){
var date = new Date();
var timeObj = { sec:date.getSeconds(), min:date.getMinutes(), hr:date.getHours() };
localStorage.setItem("timeObj", JSON.stringify(timeObj));
$('#result').append(JSON.stringify(timeObj)+' -- > Saved<br />' );
}
function retrieveTime(){
var timeObj = JSON.parse(localStorage.getItem("timeObj"));
//You have the time with you now
$('#result').append(timeObj.hr+':'+timeObj.min+':'+timeObj.sec+' --> Retrieved<br />');
}
Here is JS Fiddle Demo
I'm trying to get three different dynamic timezone clocks on my site. i've got the following js code which i found on this site (saved as myClocks.js and included on the header of my html site):
var clock1 = new Date();
var clock2 = new Date();
var clock3 = new Date();
clock2.setHours(clock2.getHours() + 3);
clock3.setHours(clock3.getHours() - 5);
clock1.getUTCHours();
clock1.getUTCMinutes();
clock1.getUTCSeconds();
clock2.getUTCHours();
clock2.getUTCMinutes();
clock2.getUTCSeconds();
clock3.getUTCHours();
clock3.getUTCMinutes();
clock3.getUTCSeconds();
How do I code the "display" to show it anywhere I want on my HTML page? For example as an id called clocks, to look like the following:
New York: 02:12:02 Paris: 17:01:24 Moscow: 22:23:42
Many thanks in advance.
<html><head></head><body>
<script language="javascript">
ourDate = new Date();
document.write("The time and date at your computer's location is: "
+ ourDate.toLocaleString()
+ ".<br/>");
document.write("The time zone offset between local time and GMT is "
+ ourDate.getTimezoneOffset()
+ " minutes.<br/>");
document.write("The time and date (GMT) is: "
+ ourDate.toGMTString()
+ ".<br/>");
</script>
</body></html>
innerHTML is what you need. Try something like:
window.onload = function(){ // It is important to wait till DOM is ready!
var clocks_str = clock3.getUTCHours()+" "+ clock3.getUTCMinutes()+" "+clock3.getUTCSeconds();
document.getElementById("clocks").innerHTML = clocks_str ;
}
And if you want it dynamic , use setInterval method , like this:
var clocks_interval;
var clocks_box;
window.onload = startClocks;
function startClocks(){
clocks_box = document.getElementById("clocks");
clocks_interval = setInterval(updateClocks , 1000); // 1000 means 1 second
}
function updateClocks (){
var clocks_str = clock3.getUTCHours()+" "+ clock3.getUTCMinutes()+" "+clock3.getUTCSeconds();
clocks_box.innerHTML = clocks_str ;
}
You can create a div or other HTML and use "innerHTML".
document.getElementById("clocks").innerHTML = clock1.getUTCHours();
I'm currently enrolled in a JavaScript class at my community college, and we're supposed to create a page with the following:
"Today's date is (date)"
"Kids Club"
"The time is (time)"
Then, I don't seem to get this part, the instructions state: "Have a link to the new kidsnew.htm page that contains the text "Go To Kids Club". Use onClick and widow.location to open kidsnew.htm.
Before switching, you should use the navigator object and the method to test for the name and version of the browser. Display the name and version of the browser with an alert box and advise the user to upgrade for better results with the new page if their browser is out of date.
The kidsnew page should contain an HTML form button that will take you back to the "kidsold.htm" page."
So. I assume that I'll need the browser verification, where you can find in the first part of the code. I don't get what else I'm supposed to be using, as we were not told of a "onClick" method in the chapter's were reading. Can anyone help me refine the code and get it to display as stated? I did most of it correctly, I think;
Here's my code:
<html>
<head>
<title>Kids Club</title>
<script type = "text/javascript" src = "brwsniff.js"></script>
<script type = "text/javascript">
<!-- hide me from older browsers>
//==============================Browser Info=================================
var browser_info = getBrowser();
var browser_name = browser_info[0];
var browser_version = browser_info[1];
var this_browser = "unknown";
if (browser_name == "msie")
{
if(browser_version < 5.5)
{
this_browser = "old Microsoft";
}
else
{
this_browser = "modern";
}
}
//end
if (browser_name == "netscape")
{
if (browser_version < 6.0){
this_browser = "old Netscape";
else
{
this_browser = "modern";
}
} //end
</script>
//=========================End Browser Info============================
//==========================Start Date Script============================
var date = new Date();
//new is keyword for object Date
//
//getting info from object Date
//
var month = date.getMonth();
var day = date.getDate();
var year = date.getYear();
var hour = date.getHours();
var minutes = date.getMinutes();
//january is month 0, think of arrays
//
month = month + 1;
//fix y2k
//
year = fixY2k(year);
//fix minutes by adding 0 infrotn if less than 10
//
minutes = fixTime(minutes);
var date_string = month + "/" + day + "/" + year;
var time_string = hour + ":" + minutes;
var date = "Today is " + date_string";
var time = "The time is " + time_string;
//y2k fix
//
function fixY2k(number) {
if (number < 1000){
number = number + 1900;
return number;
}
//time fixer
//
function fixTime(number){
if(number < 10) {
number = "0" + number;
}
return number;
}
//========================End Time Script==================================
// show me -->
</script>
</head>
<body>
<script type = "text/javascript">
<!-- hide me from older browsers
document.write(date);
</script>
//show me -->
<h1>Kids Club</h1>
<script type = "text/javascript">
<!-- hide me from older browsers
document.write(time);
</script>
//show me -->
</body>
</html>
Some comments:
> <script type = "text/javascript">
> <!-- hide me from older browsers>
That's rubbish, HTML comment delimiters were never needed to hide script element content, just remove them.
> var year = date.getYear();
You should use the getFullYear method, it avoids the two digit year issue.
> var date = "Today is " + date_string";
There is no need to declare date a second time. It's not harmful, just unnecessary. date started out as a Date object, now it's a string. That's not good programming style, just modify the existing date_string, e.g.
date_string = "Today is " + date_string";
In the body of the page you have:
> <script type = "text/javascript">
> <!-- hide me from older browsers
> document.write(date);
> </script>
> //show me -->
Note that the comment delimiters start inside the script element, then finish outside it. So the browser is left with invalid HTML and whatever happens next is a result of error correction (the same for the next script element too).
Fix that and you may have solved your problem.