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.
Related
I would like to know how my code could be displayed on a webpage instead of displayed in alert boxes, how do I do this. I understand that id's ect are needed but I am a little confused of where to start. Any help would be good. Thankyou!
<!DOCTYPE html>
<html>
<script>
//Set of variables
var nameCheck = /^[a-zA-Z\s]+$/;
//eliminates anything not relevant
var numberCheck = /^[0-9\.]+$/;
//eliminates anything not relevant
var totHours = 0;
//adds total gaming hours on one day
var dayHours = 0;
//how many on one such day set in i from 1-7
var averHours = 0;
//stores the average by dividing by the tothours by 7
var mostPerDay = 0;
//calculates day with most gamed
var mostOnDay = 0;
//Most hours on ONE day
var moreDays = " ";
//adds an s to the end of days if more than one
var mpd = 0;
//most per day
var ah = 0;
//average hours
var th = 0;
//total hours
var name = prompt("What is your name?");
//asks users name
//Make sure user inputs a name that includes letters and or spaces
while (name == "null" || isNaN(name) == false || !name.match(nameCheck)){
alert("Invalid Name!");
name = prompt("What is your name?");
}
//Greets the user by name
alert("Hello " + name );
//Ask how many hours gamed on a day
for (var i = 1; i <= 7; i++){
dayHours = prompt("How many hours have you gamed on day " + i + "?")
//Reask the question if the user inputs an invald answer
while (dayHours == null || isNaN(dayHours) || dayHours > 24 || !dayHours.match(numberCheck) || dayHours < 0){
alert("Incorrect! No letters or symbols, and make sure your input is under 24");
dayHours = prompt("How many hours have you gamed on day " + i + "?")
}
//Adds to total hours
totHours += Number(dayHours)
//Calculates days with most hours gamed
if (mostPerDay > dayHours){
}
else if (mostPerDay < dayHours){
mostPerDay = Number(dayHours);
mostOnDay = i;
}
else if (mostPerDay = dayHours){
mostOnDay += " and " + i;
mostPerDay = Number(dayHours);
}
}
//Adds 's' to the statistics if more than one day
if (isNaN(mostOnDay) == true){
moreDays = "s ";
}
//Divides the total hours by 7 to get average over those 7 days
aver = (totHours / 7);
//Calculates and rounds to the value of 1
th = totHours.toFixed(1);
ah = aver.toFixed(2);
mpd = mostPerDay.toFixed(1);
//States calculated statistics
alert("\nTotal gaming hours this week " + th + "\nAverage gaming hours this week " + ah + "\nMost on one day" + moreDays + mostOnDay + " for " + mpd + " hours." );
//Comments on average hours per day gamed
if (averHours <= 2){
alert("Healthy amount of gaming this week")
}
else if (averHours <= 24){
alert("Unhealthy amount of gaming this week")
}
</script>
</html>
There are several ways to include JavaScript in an HTML document:
Put the JavaScript code in a separate filename.js document and refer to it in the header of the HTML document (that is, between <head> and </head>) as follows: <script type="text/javascript" src="filename.js"></script>. This is the "cleanest" option as it separates functionality (JavaScript) from structure (HTML).
Put the JavaScript code directly in the header of the HTML document; that is, between <script type="text/javascript"> and </script> (no src attribute here)
In the body of the HTML document, again between <script> and </script>, for example when you want to dynamically add text with document.write('');
Changing the text in a <div id="mydiv"> can be done by accessing it via its id:
document.getElementById('mydiv').innerText = 'text';
or through the variants innerHTML, outerText or outerHTML.
For easy DOM manipulation, you may want to look into jQuery. Also, keep in mind that the JavaScript code in the header or external file will be executed immediately, which may cause errors if certain parts of the document body aren't loaded yet. jQuery offers an elegant solution by wrapping the code in
$(document).ready(function () {
// code here
});
Good luck!
A simple method to do this would be to include a link to an external javascript file:
<script src="path/myfile.js"></script>
at the bottom of your html file. If your script requires jQuery, make sure it is linked as an external script before your script. You can reference html elements in your javascript file by giving your html tags an id or class. For example:
In HTML:
<div id = "mydiv"> </div>
Select element in JS:
$('#mydiv')
If you are trying to make your web page more reactive, you may want to look into jquery. It's a lightweight javascript library that can help you make your web page more interactive. Check out the tutorial below:
http://www.w3schools.com/jquery/
I don't entirely understand your question, but just in case you are asking if the javascript will literally show up on your web page, it won't unless you display it as text. If you want to debug your javascript code, you can use developer tools on Chrome or something like it on other browsers:
https://developer.chrome.com/devtools
Can I please get any help finishing this code I did for my website. I'm using jquery and what this code does is its checking the recert date (expiry date) of an application first before a customer can re-apply again, so basically they can only re-apply within 4 weeks of their current application expiry date.
e.g. if a person application expires Aug 31 2016 that means they can only re-apply from Aug 3 2016 to Aug 31 2016 with 4 weeks to be exact. An application last for 3 years.
I provided my code and its working but I don't know if this is the right conditions and all it does is just hide the apply button if expiry date is still not up.
$(document).ready(function(){
var current = new Date();
var expiry = new Date($("#mcs_nextrecertdate").val());
if(current.getTime() > expiry.getTime()){
$("#NextButton").show();
}
else {
$("#NextButton").hide();
}
EDIT: Im testing the codes I receive from the answers based on these dates first can re-apply with 27 august 2016 and the second is a date that can't re-apply yet 20 July 2019
Given your question and explanation of your problem, I'd like to point out a few observations I've made
1. Date validation
var expiry = new Date($("#mcs_nextrecertdate").val());
Whatever #mcs_nextrecertdate is, I'll assume you've already made sure that this "input" element's value is correctly formatted. Otherwise you'll get a JS script error and the whole thing will break
2. Incorrect logic
Based on your explanation, a user can only re-certify WITHIN 4 weeks of the current application's expiry date. I'll assume that #NextButton is a submit button that triggers the new application. Based on that, this expression is wrong...
if(current.getTime() > expiry.getTime()){...}
because you're telling your app to allow users to apply for a certification AFTER the current application has expired, NOT WITHIN 4 weeks after expiration, in other words, users can ONLY re-apply after they're application expired...not before.
3. Server validation
This is just an assumption. I'll also assume this "client-side logic" is just to offer a good user experience of your app and that you are running proper server-side validation otherwise advanced users like me can easily bypass client-side validation, cheat/hack these "constraints" and even bring your application data to an inconsistent state.
Correct Logic
In order to make sure users can re-apply within 4 weeks prior to the current expiry date you need to do the following...
var now = new Date();
var expiry = new Date($("#mcs_nextrecertdate").val());//assuming this has a valid date
var startValidAppDate = new Date($("#mcs_nextrecertdate").val());
//set valid application dates
startValidAppDate.setTime(expiry.getTime() - (7 * 4 * 24 * 60 * 60 * 1000));//4 weeks to milliseconds
if(now < expiry && now > startValidAppDate){
//ok to apply
$("#NextButton").show();
}
Again, ALWAYS make sure you have strong validation on the server. Here's a working snipper...
$(function(){
$('#txtExpiryDateParent').datetimepicker({
format: "YYYY-MM-DD"
});
$("a").click(function(){
var now = new Date();
var expiry = new Date($("#txtExpiryDate").val());
var startValidAppDate = new Date($("#txtExpiryDate").val());
//set valid application dates
startValidAppDate.setTime(expiry.getTime() - (7 * 4 * 24 * 60 * 60 * 1000));//4 weeks to milliseconds
if(now < expiry && now > startValidAppDate){
$(".info.bg-success").show();
$(".info.bg-error").hide();
}
else{
$(".info.bg-success").hide();
$(".info.bg-error").show();
}
});
});
form{
background-color:#eee;
max-width:500px;
padding:30px;
margin:30px;
}
.info{
padding:20px;
border-radius:3px;
text-align:center;
margin-bottom:20px;
display:none;
}
.bg-success{
background-color:#5cb85c !important;
}
.bg-error{
background-color:#d9534f !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
<form class="center-block">
<div class="info bg-success">You're good to re-certify</div>
<div class="info bg-error">You can't certify right now</div>
<div class="form-group">
<label for="txtExpiryDate">Expiry Date</label>
<div class='input-group date' id='txtExpiryDateParent'>
<input id="txtExpiryDate" type='text' name="ExpiryDate" class="form-control"
placeholder="Expiry date..." />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<a class="btn btn-default" href="javascript:void(0)">Validate</a>
</form>
Best practices in client-side is to remove your element NOT hide it .
if(current.getTime() > expiry.getTime()){
$("#NextButton").show();
}
else {
$("#NextButton").remove();
}
Ans Best Practices in server-side are to check expiration date there and render HTML without #NextButton element.
When in doubt, always do testing:
$(document).ready(function(){
var current = new Date();
//var expiry = new Date("August 1, 2014");
var expiry = new Date("August 13, 2017");
if(current.getTime() > expiry.getTime()){
$("#NextButton").show();
}
else {
$("#NextButton").hide();
}
});
I currently have the following code showing:
<h1 id="header1" class="loginhead">Welcome to the <%=formFields.getDisplayValue("programName")%> Registration Site, .</h1>
I need to replace it with:
<h1 id="header2" class="loginhead" >The <%=formFields.getDisplayValue("programName")%> Registration Site, is now closed.</h1>
I need the replace to happen when the date and time are 7/15/15 11:59PM PT
Any way to do this using Jquery, JSP or Javascript?
Update**
<h1 id="header" class="loginhead" ><span id='welcome'></span><span id='welcome2'></span> <%=formFields.getDisplayValue("programName")%> Registration Site <span id='closed'></span> </h1>
<script>
var now = new Date().getTime(); //Return the number of milliseconds since 1970/01/01:
var epochTimeJul15_1159pm = 1437019199000; // number of milliseconds since 1970/01/01 at Jul 15_11:59:59pm. See http://www.epochconverter.com/.
var timeTillChange = epochTimeJul15_1159pm - now;
function changeHeader(){
document.getElementById('closed').innerHTML = ' is now closed.'; //change the html/text inside of the span with the id closed'.
}
function changeHeader1()
{
if(epochTimeJul15_1159pm <= now)
{
document.getElementById('welcome').innerHTML = 'The ';
}
}
function changeHeader2()
{
if(now < epochTimeJul15_1159pm)
{
document.getElementById('welcome2').innerHTML = 'Welcome to the ';
}
}
setTimeout(changeHeader, timeTillChange); //will wait to call changeHeader function until timeTillChange milliseconds have occured.
setTimeout(changeHeader1, timeTillChange);
setTimeout(changeHeader2, timeTillChange);
</script>
First make it easier to use javascript to edit your html. We will do this by creating an empty span to insert the closed message into:
<h1 id="header" class="loginhead" >Welcome to the <%=formFields.getDisplayValue("programName")%> Registration Site <span id='closed'></span> </h1>
Now in your javascript section:
var now = new Date().getTime(); //Return the number of milliseconds since 1970/01/01:
var epochTimeJul15_1159pm = 1437019199000; // number of milliseconds since 1970/01/01 at Jul 15_11:59:59pm. See http://www.epochconverter.com/.
var timeTillChange = epochTimeJul15_1159pm - now;
function changeHeader(){
document.getElementById('closed').innerHTML = ' is now closed.'; //change the html/text inside of the span with the id closed'.
}
setTimeout(changeHeader, timeTillChange); //will wait to call changeHeader function until timeTillChange milliseconds have occured.
This will make the header get edited live as soon as the clock hits 11:59:59.
if ($.now >= dateLimit){
$("#header1").hide(0);
$("#header2").show(0);
}
This would be a general jquery way to do this, you could setup the two elements to be hidden or shown accordingly in your css.
This would do it upon page load, I am not exactly sure how to implement a dynamic version of this.
That's how you can do dynamically with JavaScript. Working Plunker
You can just compare two date and change innerHTML of header.
<html>
<head>
<script>
function setHeader(){
var d1 = new Date("7/15/15 11:57"); // change your dates here
var d2 = new Date("7/15/15 11:58"); // change your dates here
var header = document.getElementById("header");
if(d1 > d2){
header.innerHTML = "Welcome to the " + <%=formFields.getDisplayValue("programName")%> + " Registration Site."
} else {
header.innerHTML = "Welcome to the " + <%=formFields.getDisplayValue("programName")%> + " Registration Site, is now closed. "
}
}
</script>
</head>
<body onload="setHeader()">
<h1 id="header" class="loginhead"></h1>
</body>
</html>
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.