Beginner JavaScript help(functions) - javascript

I'm having some trouble copying the scripts and HTML from the calender on refdesk.com. I need put the JavaScript on a different style sheet and use those functions to recreate the calender on a HTML page. Here is what I have so far, any tips will help. This is a homework assignment so I'm not looking for the answers.
JavaScript -
function initialize()
{
buildCal();
updateCalender();
}
var themonths = ['January','February','March','April','May','June',
'July','August','September','October','November','December'];
var todaydate = new Date();
var curmonth = todaydate.getMonth() + 1; //get current month (1-12)
var curyear = todaydate.getFullYear(); //get current year
function buildCal(month, year, cM, cH, cDW, cD, border)
{
var mn = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var dim = [31,0,31,30,31,30,31,31,30,31,30,31];
var firstDaySelectedMonth = new Date(year, month - 1, 1); //DD replaced line to fix date bug when current day is 31st
firstDaySelectedMonth.od=firstDaySelectedMonth.getDay() + 1; //DD replaced line to fix date bug when current day is 31st
var todaydate = new Date(); //DD added
var scanfortoday = (year == todaydate.getFullYear() && month == todaydate.getMonth() + 1) ? todaydate.getDate() : 0; //DD added
dim[1] = (((firstDaySelectedMonth.getFullYear() % 100 != 0) && (firstDaySelectedMonth.getFullYear() %4 == 0)) || (firstDaySelectedMonth.getFullYear() % 400 == 0)) ? 29 : 28;
var t = '<div class="' + cM + '"><table class="' + cM + '" cols="7" cellpadding="0" border="' + brdr + '" cellspacing="0"><tr align="center">';
t += '<td colspan="7" align="center" class="' + cH + '">' + mn[month - 1] + ' - ' + year + '</td></tr><tr align="center">';
for (s = 0; s < 7; s++)
{
t += '<td class="' + cDW + '">' + "SMTWTFS".substr(s,1) + '</td>';
t += '</tr><tr align="center">';
}
for(i = 1;i <= 42; i++)
{
var x = ((i-firstDaySelectedMonth.od >= 0) && (i-firstDaySelectedMonth.od < dim[month -1 ])) ? i-firstDaySelectedMonth.od + 1 : ' ';
if (x == scanfortoday) //DD added
{
x = '<span id="today">' + x + '</span>'; //DD added
t += '<td class="' + cD + '">' + x +'</td>';
}
if(((i) % 7 == 0) && (i < 36))
{
t += '</tr><tr align="center">';
}
}
return t += '</tr></table></div>';
}
// update calender function
function updateCalendar(theSelection)
{
var themonth = parseInt(theSelection[theSelection.selectedIndex].value) + 1;
var calendarstr = buildCal(themonth, curyear, "main", "month", "daysofweek", "days", 0);
if (document.getElementById)
{
document.getElementById("calendarspace").innerHTML = calendarstr;
}
document.write('<option value="'+(curmonth - 1) + '" selected="yes">Current Month</option>');
for (i = 0; i < 12; i++) //display option for 12 months of the year
{
document.write('<option value="' + i + '">' + themonths[i] + ' ' + curyear + '</option>');
}
}
HTML -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="refdesk.css">
<script src="refdesk.js"></script>
</head>
<body onload="initialize()">
<!-- CALENDAR START -->
<form>
<div id="choicespace">
<p>(This will be replaced with JavaScript-generated HTML)</p>
<select onchange="updatecalendar(this.options)">
<script>
updatecalendar(theselection);
</script>
<option value="1" selected="yes">Current Month</option><option value="0">January 2013</option><option value="1">February 2013</option><option value="2">March 2013</option><option value="3">April 2013</option><option value="4">May 2013</option><option value="5">June 2013</option><option value="6">July 2013</option><option value="7">August 2013</option><option value="8">September 2013</option><option value="9">October 2013</option><option value="10">November 2013</option><option value="11">December 2013</option>
</select>
</div>
<div id="calendarspace">
<p>(This will be replaced with JavaScript-generated HTML)</p>
</div>
</form>
</body>
</html>

First, try to figure how your javascript code really work. Take a look on calendar in javascript as a simple example.

Personally I would indent more to keep things organized. Another thing I would do is just make shorter variables because sometimes i find myself coding wrong because of my huge variable names.

Related

Run a javascript from a html table cell

I am using asp.net core 5 and I have the following cell in a table -
<td id="actionId" class="text-left">
<input hidden id="renewalDueId" type="hidden" asp-for="#clinic.RenewalDue" class="form-control" />
<input hidden id="nextRenewalDueAtId" asp-for="#clinic.VaccClinic.NextRenewalDueAt" class="form-control" />
<input hidden id="dedesignatedDateId" asp-for="#clinic.VaccClinic.DedesignationDate" class="form-control" />
<div id="designationPlaceHolderHere"></div>
Training Status: <br /><br />
Annual Returns Figures:
#if (clinic.NumberOfVaccinations.HasValue)
{
<label>#clinic.NumberOfVaccinations.Value.ToString()</label>
if (clinic.NumberOfAdverseEvents.HasValue)
{
<label> - #clinic.NumberOfAdverseEvents.Value.ToString()</label>
}
else
{
<label> - 0</label>
}
}
else
{
<label style="background-color:red">
Not Submitted
</label>
}
</td>
I am trying to call a javascript function and add html at designationplaceholder for each record in the table.
I have tried -
$('tr').each(function (i, item) {
var html = DesignationStatus($('#dedesignatedDateId').val(), $('#renewalDueId').val(), $('#nextRenewalDueAtId').val(), #(ViewBag.NumberOfDays));
$('#designationPlaceHolderHere').html(html);
});
Doesn't work properly.
I want to call the function, for each record, passing the appropriate values for each record.
Any ideas?
Thanks
[UPDATE]
This is the function I call -
function DesignationStatus(dedesignatedDate, renewalDue, nextRenewalDue, numberOfDays) {
var isRenewalDue = (renewalDue === 'true')
//Get today's date
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var todaysDate = d.getFullYear() + '/' +
(month < 10 ? '0' : '') + month + '/' +
(day < 10 ? '0' : '') + day;
//Create next renewal due date display value.
var reDate = new Date(nextRenewalDue);
var reDay = reDate.getDate();
var reMonth = reDate.getMonth() + 1;
var displayRenewalDate = (reDay < 10 ? '0' : '') + reDay + '/' + (reMonth < 10 ? '0' : '') + reMonth + '/' + reDate.getFullYear()
//Create de-designation date display value.
var deDate = new Date(dedesignatedDate);
var deDay = deDate.getDate();
var deMonth = deDate.getMonth() + 1;
var displayDedesignationDate = (deDay < 10 ? '0' : '') + deDay + '/' + (deMonth < 10 ? '0' : '') + deMonth + '/' + deDate.getFullYear()
//Calculate what one day is
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
//Parse the number off days passed in
var numOfDays = parseInt(numberOfDays);
//If no number has been passed in set to default of 90.
if (isNaN(numberOfDays)) {
numOfDays = 90;
}
//Start html string
var html = '<div>'
html += ' <label>Designation status:</label>'
html += ' </div>'
html += ' <div>'
//Get rest of html dependant on due date etc.
if (dedesignatedDate != null && dedesignatedDate != "") {
html += ' <div class="alert alert-danger" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>De-designated on</label>' + ' ' + displayDedesignationDate
}
else {
if (nextRenewalDue != null && nextRenewalDue != "") {
var today = new Date();
var renewal = new Date();
today = Date.parse(todaysDate);
renewal = Date.parse(nextRenewalDue);
if (renewal > today) {
if (!isRenewalDue) {
html += ' <div class="alert alert-success" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Active</label>'
}
else {
html += ' <div class="alert alert-warning" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Due to renew - renew before </label>' + ' ' + displayRenewalDate
}
}
else if (renewal < today) {
//Work out the number of days between renewal and today's date
var diffDays = Math.round(Math.abs(((new Date(today).getTime()) - (new Date(renewal).getTime())) / (oneDay)));
if (diffDays < numOfDays) {
html += ' <div class="alert alert-danger" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Inactive - lapsed on </label>' + ' ' + displayRenewalDate;
}
else {
html += ' <div class="alert alert-danger" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Inactive</label>'
}
}
}
}
//Finish off the html string
html += ' </div>'
html += ' </div>'
html += '</div>'
//return html strin
return html
}
<td id="actionId" class="text-left" onclick="DesignationStatus('#clinic.VaccClinic.DedesignationDate','#clinic.RenewalDue','#clinic.VaccClinic.NextRenewalDueAt','#ViewBag.NumberOfDays')">
<input hidden id="renewalDueId" type="hidden" asp-for="#clinic.RenewalDue" class="form-control" />
<input hidden id="nextRenewalDueAtId" asp-for="#clinic.VaccClinic.NextRenewalDueAt" class="form-control" />
<input hidden id="dedesignatedDateId" asp-for="#clinic.VaccClinic.DedesignationDate" class="form-control" />
<div id="designationPlaceHolderHere"></div>
Training Status: <br /><br />
Annual Returns Figures:
#if (clinic.NumberOfVaccinations.HasValue)
{
<label>#clinic.NumberOfVaccinations.Value.ToString()</label>
if (clinic.NumberOfAdverseEvents.HasValue)
{
<label> - #clinic.NumberOfAdverseEvents.Value.ToString()</label>
}
else
{
<label> - 0</label>
}
}
else
{
<label style="background-color:red">
Not Submitted
</label>
}
This should call your javascript function. Also never use the same id="dedesignatedDateID".

JavaScript class did not function in asp.net

I have created a javascript function in my aspx page..
below are the sample code,
<script type="text/javascript">
$(document).ready(function () {
console.log("ready!");
var output = [];
var yr = 1950;
for (var i = 0; i <= 70; i++) {
if (i == 0) {
output[i] = '<option value="0" selected="selected"> Choose Year</option>';
}
else {
output[i] = '<option value="' + (parseInt(1950) + parseInt(i - 1)) + '">' + (parseInt(1950) + parseInt(i - 1)) + '</option>';
}
}
$('#yearid').get(0).innerHTML = output.join('');
});
$("#yearid").change(function () {
var select = $("#yearid option:selected").val();
$("#yearval").val(select);
});
</script>
I would like this function execute in the property such as
<div class="col-md-4 form-group">
<span>Year : </span>
<select id="yearid" class="form-control" runat="server">
</select>
<input id="yearval" type="hidden" runat="server"/>
</div>
As the code running, the javascript function above should be executed and display the " Choose Year" propery inside as shown above.
I try to run this code but nothing happens to the property. Any help would be appreciated. Thank u.
Your code seems to be working as below. However you may be missing the jQuery script so you can check if that exists.
$(document).ready(function () {
console.log("ready!");
var output = [];
var yr = 1950;
for (var i = 0; i <= 70; i++) {
if (i == 0) {
output[i] = '<option value="0" selected="selected"> Choose Year</option>';
}
else {
output[i] = '<option value="' + (parseInt(1950) + parseInt(i - 1)) + '">' + (parseInt(1950) + parseInt(i - 1)) + '</option>';
}
}
$('#yearid').get(0).innerHTML = output.join('');
});
$("#yearid").change(function () {
var select = $("#yearid option:selected").val();
$("#yearval").val(select);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-4 form-group">
<span>Year : </span>
<select id="yearid" class="form-control" runat="server">
</select>
<input id="yearval" type="hidden" runat="server"/>
</div>

Parsing to a table in Javascript

I'm trying to create a calander that can later be styled with CSS. Here is the JS and HTML codes. There is a CSS stylesheet as well but its just used for color and positioning. In the Javascript, I would like to build the table based off the first and last days of the month and insert a new row at the end of each week. As is the Javascript does nothing. When you remove the first if statement, it seems to iterate only once. I'm not sure where I'm screwing up in trying to create the table.
function setDate() {
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
var day = today.getDate();
document.getElementById("myDay").value = day;
document.getElementById("myMonth").value = month;
document.getElementById("myYear").value = year;
}
function buildCalendar() {
var firstDate = new Date(document.getElementById("myYear").value, document.getElementById("myMonth").value, 1);
var weekDay = firstDate.getDay();
var theDate = firstDate.getDate();
var theMonth = firstDate.getMonth();
var theYear = firstDate.getFullYear();
var newDay = new Date(theYear, theMonth + 1, 1);
var lastDate = new Date(newDay - 1);
var lastDay = lastDate.getDate();
document.write("<table class='caltable' border='1'><tr><th>");
document.write("<tr><th>Sunday</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th>");
document.write("</th></tr>");
var col = 0;
for (var i = theDate; i < lastDay + 1; i++) {
if (col == 0) {
document.write("<tr><td>" + i "</td>");
}
if (col == 6) {
document.write("<td>" + i + "</td></tr>");
col == 0;
} else {
document.write("<td>" + i + "</td>");
col++;
}
}
document.write("</table>");
}
function getMonthName() {
var e = getElementById("myMonth").selectedIndex;
var monthName = e.options[e.selectedIndex].text;
return monthName;
}
Here is the HTML file. It's basically just a wrapper div with some other divs inside for holding the calendar eventually a scheduler, as well as the current date. Right now I'm simply trying to get the the table (see the javascript) to build. Ideally it would be in the div with the id "bottomLeft".
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel = "stylesheet" type = "text/css" href = "./CSS/calendar.css">
<script type = "text/javascript" src = "./Calendar/calendar.js"></script>
<script type = "text/javascript" src = "./Calendar/task.js"></script>
</head>
<body onLoad = "setDate(); buildCalendar();">
<div id = "wrapper">
<div id = "left"> Left Div </div>
<div id = "right"> Right Div </div>
<div id = "bottomLeft"> Shows calendar </div>
<div id = "topLeft"> Day:<input id = "myDay" type="number" min = "1" max = "31">Month:<select id = "myMonth"><option value = "0">January</option> <option value = "1">February</option><option value = "2">March</option><option value = "3">April</option><option value = "4">May</option><option value = "5">June</option><option value = "6">July<option value = "7">August</option><option value = "8">September</option><option value = "9">October</option><option value = "10">November</option><option value = "11">December</option></select> Year:<input id = "myYear" type = "number" min = "100"> TopLeft Div shows form components for date </div>
<div id = "topRight"> Shows the form to add task </div>
<div id = "bottomRight"> Show list of tasks </div>
</div>
</body>
</html>
In addition to the mistakes Ceesie123456 mentioned, you need to remove the extra <tr><th> from the opening table tag string. As a means of getting the calendar into the bottomLeft div, you can use set the element's innerHTML property. Finally, you're missing a piece of logic which check for when the end of the calendar is not the end of a row, which means the table won't line up correctly. So, an example:
function buildCalendar(){
var firstDate = new Date(document.getElementById("myYear").value, document.getElementById("myMonth").value, 1);
var weekDay = firstDate.getDay();
var theDate = firstDate.getDate();
var theMonth = firstDate.getMonth();
var theYear = firstDate.getFullYear();
var newDay = new Date(theYear, theMonth + 1, 1);
var lastDate = new Date(newDay - 1);
var lastDay = lastDate.getDate();
var tableString = ("<table class='caltable' border='1'>");
tableString = tableString + ("<thead><tr><tr><th>Sunday</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th></tr></thead>");
tableString = tableString + "<tbody>";
var col = 0;
for (var i = theDate; i <= lastDay; i++)
{
if(col == 0)
{
tableString = tableString + ("<tr>");
}
tableString = tableString + "<td>" + i + "</td>";
if (col == 6 || i == lastDay)
{
tableString = tableString + ("</tr>");
col = 0;
}
else
{
col++;
}
}
tableString = tableString + ("</tbody></table>");
document.getElementById("bottomLeft").innerHTML = tableString;
}
U made a few mistakes in ur Javascript code.
if (col == 6)
{
document.write("<td>" + i + "</td></tr>");
col == 0; //this should be changed to col = 0; with col = 0; u set col to 0.
}
and
if(col == 0)
{
document.write("<tr><td>" + i "</td>");
}
u should change it to:
if(col == 0)
{
document.write("<tr><td>" + i + "</td>"); // combine string with variable and string.
}

Splitting an array

I have two javascript functions, the first one is working, teh second is working but not echoing the correct value in the hidden inputs.
Ive manage to get the last hidden input value correct but I'm not sure how
var customTicketsArr = Array();
function EditEventAddTicket(){
alertWrongTime = false;
var TicketName = jQuery("#ticketname").val();
var TicketPrice = jQuery("#ticketprice").val();
var ticketquantity = jQuery("#ticketquantity").val();
var storeString = "TicketName" + TicketName + "TicketPrice" + TicketPrice + "Quantity" + ticketquantity + '';
customTicketsArr.push(storeString);
EditEventUpdateTickets(true);
}
function EditEventUpdateTickets(fade){
jQuery("#custom_tickets_string").val(customTicketsArr);
var output = "";
var style = "";
for (i = customTicketsArr.length-1; i >= 0; i--){
ticketname = customTicketsArr[i].split("TicketName");
ticketprice = customTicketsArr[i].split("TicketPrice");
ticketquantity = customTicketsArr[i].split("Quantity");
if(fade){
if (customTicketsArr.length - 1 == i){
style = "display: none; ";
var fadeInDiv = i;
} else {
style = "";
}
}
if (i % 2 == 1) { style += "background-color: #660000; "}
html = "<div id='customticket" + i + "' class='customeventbase' style='" + style + "'>";
html += '<input type="hidden" name="customTicketid[' + i + '][Name]" id="customticketName' + i + '" value="'+ ticketname + '" />';
html += '<input type="hidden" name="customTicketid[' + i + '][Price]" id="customticketPrice' + i + '" value="' +ticketprice[1] +'" />';
html += '<input type="hidden" name="customTicketid[' + i + '][Quantity]" id="customticketQuantity' + i + '" value="'+ ticketquantity[1] +'" />';
html += '<button class="customeventdel" type="button" onClick="EditEventRemoveDate(' + i + ')"></button>';
html += '<div class="clear"></div>';
html += '</div>\n';
output += html;
}
output += "<input type='hidden' id='custom_ticket_info' name='custom_ticket_info' value='" + customTicketsArr + "' />";
jQuery("#custom_ticket_container").html(output);
if(fade){
setTimeout("EditEventfadeInDiv(" + fadeInDiv +")", 10);
}
}
this outputs:
<div style="background-color: #660000; " class="customeventbase" id="customticket1">
<input type="hidden" value=",testTicketPrice50Quantity44" id="customticketName1" name="customTicketid[1][Name]">
<input type="hidden" value="undefined" id="customticketPrice1" name="customTicketid[1][Price]">
<input type="hidden" value="44" id="customticketQuantity1" name="customTicketid[1][Quantity]">
<button onclick="EditEventRemoveDate(1)" type="button" class="customeventdel"></button>
<div class="clear"></div></div>
the values for the first two hidden fields are incorrect
They're not incorrect values - split() is doing exactly what it is supposed to - returning an array of substrings after removing the separator.
With your string structure, splitting on TicketName will give you two strings - the substring before the separator and the substring after - TicketName itself is not included.
Thus, for the string "TicketNametestTicketPrice50Quantity44", you will get "" and "testTicketPrice50Quantity44" when you split on "TicketName" . Splitting the same string on TicketPrice will give you "TicketNametest" and "50Quantity44".
I'd suggest putting objects into your array instead -
var storeObject = {
"TicketName" : TicketName,
"TicketPrice" : TicketPrice,
"Quantity" : ticketquantity
};
customTicketsArr.push(storeObject);
You can then get back the data as:
for (i = customTicketsArr.length-1; i >= 0; i--){
var currentObject = customTicketsArr[i];
var ticketname = currentObject.TicketName;
var ticketprice = currentObject.TicketPrice;
var ticketquantity = currentObject.Quantity;
//do other stuff here
}
why do you save it as a string? I would recommend storing it in an object:
function EditEventAddTicket(){
alertWrongTime = false;
var TicketName = jQuery("#ticketname").val();
var TicketPrice = jQuery("#ticketprice").val();
var ticketquantity = jQuery("#ticketquantity").val();
var ticket = {"TicketName": TicketName, "TicketPrice": TicketPrice, "Quantity": ticketquantity};
customTicketsArr.push(ticket);
EditEventUpdateTickets(true);
}
and then you can simply load the data:
for (i = customTicketsArr.length-1; i >= 0; i--){
ticketname = customTicketsArr[i].TicketName;
ticketprice = customTicketsArr[i].TicketPrice;
ticketquantity = customTicketsArr[i].Quantity;
// ...
}
Why not just make a two dimensional array?
var customTicketsArr = Array();
function EditEventAddTicket() {
customTicketsArr.push({
'name' : jQuery("#ticketname").val(),
'price' : jQuery("#ticketprice").val(),
'qty' : jQuery("#ticketquantity").val()
});
}

Why does my alarmclock script stop working?

It only works once. At second button click, nothing occurs.
If I change budilnik variable at i_budilnik or var budilnik, it doesn't work even once!
Where is the problem?
<div>
<form name="alert">
<input type="text" name="hour" />
<input type="text" name="min" />
<input type="button" value="ok" onclick="budilnik(this.form)">
</form><font color=#660000 size=20 face=Tahoma><span id="hours"></span>
</div>
<script type="text/javascript">
function budilnik(form) {
budilnik = 1;
min = form.min.value;
hour = form.hour.value;
}
obj_hours = document.getElementById("hours");
function wr_hours() {
time = new Date();
time_min = time.getMinutes();
time_hours = time.getHours();
time_wr = ((time_hours < 10) ? "0" : "") + time_hours;
time_wr += ":";
time_wr += ((time_min < 10) ? "0" : "") + time_min;
time_wr = time_wr;
obj_hours.innerHTML = time_wr;
if (i_budilnik == 1) {
if (min == time_min) {
if (hour == time_hours) {
alert('welldone');
budilnik = 0;
}
}
}
}
wr_hours();
setInterval("wr_hours();", 1000);
</script>
You call the function wr_hours(); only once... with the onclick budilnik is called, but that doesn't touch wr_hours again. The first time the code is run, because the page is loaded, but after that, with the onclick only the values of min and hour are set again.
edit: you shouldn't call your form "alert", since that's a reserved word in javascript, same for the variable min. also: the variables min and hour are defined in the function budilnik, but they're not known outside this scope. I also renamed the variable budilnik to a global variable justonce to make sure you can check it outside the scope of budilnik. I rewrote your code a bit:
<html>
<body>
<div>
<form name="frm">
<input type="text" name="hour" />
<input type="text" name="mins"/>
<input type="button" value="ok" onclick="justonce=1;">
</form>
<font color=#660000 size=20 face=Tahoma><span id="hours"></span></font>
</div>
</body>
</html>
<script type="text/javascript">
obj_hours=document.getElementById("hours");
justonce=0;
function wr_hours()
{
time=new Date();
time_min=time.getMinutes();
time_hours=time.getHours();
time_wr=((time_hours<10)?"0":"")+time_hours;
time_wr+=":";
time_wr+=((time_min<10)?"0":"")+time_min;
obj_hours.innerHTML=time_wr;
if (justonce==1 && frm.mins.value==time_min && frm.hour.value==time_hours) {
alert('welldone');
justonce=0;
}
}
setInterval("wr_hours();",1000);
</script>
Your function wr_hours could be a lot shorter by the way:
function wr_hours()
{
time=new Date();
obj_hours.innerHTML=("%02d",time.getHours())+":"+("%02d",time.getMinutes());
if (justonce==1
&& frm.mins.value==time.getMinutes()
&& frm.hour.value==time.getHours()) {
alert('welldone');
justonce=0;
}
}
How about this?
You can't hear the"alarm" in this code, so you have to download the sound you like, rewrite a part of the code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=shift_jis">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<bgsound id="bgm" src="222.mid" loop="-1">
<TITLE>Yokai clock~The digital clock changes to the analogue one!?~</TITLE>
<SCRIPT type="text/javascript">
<!--
var flg =0;
function timeCheck(){
Now = new Date();
Hour = Now.getHours();
Min = Now.getMinutes();
Sec = Now.getSeconds();
if(Hour <= 9) {
Hour = "\u0020" + Hour;
  }
    if(Min <= 9) {
Min = "0" + Min;
  }
if(Sec <= 9) {
Sec = "0" + Sec;
  }
document.sampleForm.dspTime.value=Hour + ":" + Min + ":" + Sec;
if((flg == 1)&&(document.sampleForm.alarmH.value == Hour)&&(document.sampleForm.alarmM.value == Min)){
document.getElementById('bgCol').value="333.wav", selectBgm(document.getElementById('bgCol')),
document.getElementById('star_clock').style.visibility="hidden", document.getElementById('clock').style.visibility="visible";
flg=-1; //*One figure other than 0 and 1
  }
}
function changeFlg(){
if(flg == 0){
    document.sampleForm.setAlarm.value=" alarmOFF ";
document.getElementById("bgCol").value="";
        selectBgm(document.getElementById('bgCol'));
     flg =1;
}else{
document.sampleForm.setAlarm.value=" alarm ON ";
document.getElementById("bgms").reset();
selectBgm(document.getElementById('bgCol'));
document.getElementById('star_clock').style.visibility="visible";
document.getElementById('clock').style.visibility="hidden";
       flg =0;
}
}
setInterval(timeCheck,100);
window.onload = timeCheck;
//-->
</SCRIPT>
<script type="text/javascript">
<!--
function selectBgm(e){
var selectedIndex = e.selectedIndex;
document.getElementById("bgCol").style.background=e[selectedIndex].style.backgroundColor;
bgm.src= e[selectedIndex ].value;
document.getElementById("bgCol").value=e[selectedIndex].value;
}
//-->
</script>
</head>
<BODY color="gold" bgcolor="black">
<div id="clock" style="visibility:hidden">
<div id="Od" style="position:absolute;top:0px;left:0px">
<div style="position:relative">
</div>
</div>
<div id="Of" style="position:absolute;top:0px;left:0px">
<div style="position:relative">
</div>
</div>
<div id="Oh" style="position:absolute;top:0px;left:0px">
<div style="position:relative">
</div>
</div>
<div id="Om" style="position:absolute;top:0px;left:0px">
<div style="position:relative">
</div>
</div>
<div id="Os" style="position:absolute;top:0px;left:0px">
<div style="position:relative">
</div>
</div>
</div>
<script type="text/javascript">
(function(){
"use strict";
function $(sel)
{
return document.getElementById(sel);
}
function $$(sel)
{
if (typeof document.getElementsByClassName === 'undefined')
{
return document.getElementsByName(sel);
}
return document.getElementsByClassName(sel);
}
var dCol = '00ff00', //date colour.
sCol = 'ff0000', //seconds colour.
mCol = '008000', //minutes colour.
hCol = '008000', //hours colour.
fCol = '0000ff', //face color
ClockHeight = 40,
ClockWidth = 40,
ClockFromMouseY = 0,
ClockFromMouseX = 100,
d = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
m = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
date = new Date(),
day = date.getDate(),
year = date.getYear() + 1900;
var TodaysDate = " " + d[date.getDay()] + " " + day + " " + m[date.getMonth()] + " " + year;
var D = TodaysDate.split('');
var H = '...';
H = H.split('');
var M = '....';
M = M.split('');
var S = '.....';
S = S.split('');
var Face = '1 2 3 4 5 6 7 8 9 10 11 12',
font = 'Helvetica, Arial, sans-serif',
size = 1,
speed = 0.6;
Face = Face.split(' ');
var n = Face.length;
var a = size * 10;
var ymouse = 0,
xmouse = 0,
scrll = 0,
props = '<span style="font-family:' + font + ';font-size:' + size + 'em; color:#' + fCol + '">',
props2 = '<span style="font-family:' + font + ';font-size:' + size + 'em; color:#' + dCol + '">';
var Split = 360 / n;
var Dsplit = 360 / D.length;
var HandHeight = ClockHeight / 4.5;
var HandWidth = ClockWidth / 4.5;
var HandY = -7,
HandX = -2.5,
step = 0.06,
currStep = 0,
y = [],
x = [],
Y = [],
X = [],
Dy = [],
Dx = [],
DY = [],
DX = [];
var i;
for (i = 0; i < n; i++)
{
y[i] = 0;
x[i] = 0;
Y[i] = 0;
X[i] = 0;
}
for (i = 0; i < D.length; i++)
{
Dy[i] = 0;
Dx[i] = 0;
DY[i] = 0;
DX[i] = 0;
}
var wrapper = $('clock');
var html = ''
// Date wrapper
html = '';
for (i = 0; i < D.length; i++)
{
html += '<div class="Date" name="Date" style="position:absolute;top:0px;left:0;height:' + a + ';width:' + a + ';text-align:center">' + props2 + D[i] + '</span></div>';
}
$('Od').children[0].innerHTML = html;
// Face wrapper
html = '';
for (i = 0; i < n; i++)
{
html += '<div class="Face" name="Face" style="position:absolute;top:0px;left:0;height:' + a + ';width:' + a + ';text-align:center">' + props + Face[i] + '</span></div>';
}
$('Of').children[0].innerHTML = html;
// Hours wrapper
html = '';
for (i = 0; i < H.length; i++)
{
html += '<div class="Hours" name="Hours" style="position:absolute;width:16px;height:16px;font-family:Arial;font-size:16px;color:' + hCol + ';text-align:center;font-weight:bold">' + H[i] + '</div>';
}
$('Oh').children[0].innerHTML = html;
// Minute wrapper
html = '';
for (i = 0; i < M.length; i++)
{
html += '<div class="Minutes" name="Minutes" style="position:absolute;width:16px;height:16px;font-family:Arial;font-size:16px;color:' + mCol + ';text-align:center;font-weight:bold">' + M[i] + '</div>';
}
$('Om').children[0].innerHTML = html;
// Seconds wrapper
html = '';
for (i = 0; i < S.length; i++)
{
html += '<div class="Seconds" name="Seconds" style="position:absolute;width:16px;height:16px;font-family:Arial;font-size:16px;color:' + sCol + ';text-align:center;font-weight:bold">' + S[i] + '</div>';
}
$('Os').children[0].innerHTML = html;
// Mouse move event handler
function Mouse(evnt)
{
if (typeof evnt === 'undefined')
{
ymouse = event.Y + ClockFromMouseY;
xmouse = event.X + ClockFromMouseX;
}
else
{
ymouse = evnt.clientY + ClockFromMouseY;
xmouse = evnt.clientX + ClockFromMouseX;
}
}
document.onmousemove = Mouse;
function ClockAndAssign()
{
var time = new Date();
var secs = time.getSeconds();
var sec = -1.57 + Math.PI * secs / 30;
var mins = time.getMinutes();
var min = -1.57 + Math.PI * mins / 30;
var hr = time.getHours();
var hrs = -1.575 + Math.PI * hr / 6 + Math.PI * parseInt(time.getMinutes(), 10) / 360;
$('Od').style.top = window.document.body.scrollTop;
$('Of').style.top = window.document.body.scrollTop;
$('Oh').style.top = window.document.body.scrollTop;
$('Om').style.top = window.document.body.scrollTop;
$('Os').style.top = window.document.body.scrollTop;
for (i = 0; i < n; i++)
{
var F = $$('Face')[i];
F.style.top = y[i] + ClockHeight * Math.sin(-1.0471 + i * Split * Math.PI / 180) + scrll;
F.style.left = x[i] + ClockWidth * Math.cos(-1.0471 + i * Split * Math.PI / 180);
}
for (i = 0; i < H.length; i++)
{
var HL = $$('Hours')[i];
HL.style.top = y[i] + HandY + (i * HandHeight) * Math.sin(hrs) + scrll;
HL.style.left = x[i] + HandX + (i * HandWidth) * Math.cos(hrs);
}
for (i = 0; i < M.length; i++)
{
var ML = $$('Minutes')[i].style;
ML.top = y[i] + HandY + (i * HandHeight) * Math.sin(min) + scrll;
ML.left = x[i] + HandX + (i * HandWidth) * Math.cos(min);
}
for (i = 0; i < S.length; i++)
{
var SL = $$('Seconds')[i].style;
SL.top = y[i] + HandY + (i * HandHeight) * Math.sin(sec) + scrll;
SL.left = x[i] + HandX + (i * HandWidth) * Math.cos(sec);
}
for (i = 0; i < D.length; i++)
{
var DL = $$('Date')[i].style;
DL.top = Dy[i] + ClockHeight * 1.5 * Math.sin(currStep + i * Dsplit * Math.PI / 180) + scrll;
DL.left = Dx[i] + ClockWidth * 1.5 * Math.cos(currStep + i * Dsplit * Math.PI / 180);
}
currStep -= step;
}
function Delay()
{
scrll = 0;
Dy[0] = Math.round(DY[0] += ((ymouse) - DY[0]) * speed);
Dx[0] = Math.round(DX[0] += ((xmouse) - DX[0]) * speed);
for (i = 1; i < D.length; i++) {
Dy[i] = Math.round(DY[i] += (Dy[i - 1] - DY[i]) * speed);
Dx[i] = Math.round(DX[i] += (Dx[i - 1] - DX[i]) * speed);
}
y[0] = Math.round(Y[0] += ((ymouse) - Y[0]) * speed);
x[0] = Math.round(X[0] += ((xmouse) - X[0]) * speed);
for (i = 1; i < n; i++) {
y[i] = Math.round(Y[i] += (y[i - 1] - Y[i]) * speed);
x[i] = Math.round(X[i] += (x[i - 1] - X[i]) * speed);
}
ClockAndAssign();
setTimeout(Delay, 20);
}
Delay();
}());
</script>
<form id="bgms" style="text-align:right">
<SELECT id="bgCol" style="background:#87cefa"; onchange="selectBgm(this);">
<OPTION style="background:silver" value="" >STOP</OPTION>
<OPTION style="background:#87cefa" value="222.mid" selected>CLASSIC</OPTION>
<OPTION style="background:yellowgreen" value="333.wav">ALARM</OPTION>
</SELECT>
</form>
<FORM NAME="sampleForm" style="text-align:center">
 <font id="star_clock">
<INPUT id="Alarmy" type="text"STYLE="color:deeppink; background-color:black; font-size:25px; border:none;" size=7 NAME="dspTime">
 </font>
<br><br>
<br><br>
 <div>
★
<INPUT type="text" name="alarmH" size=2 value="00">
<INPUT type="text" name="alarmM" size=2 value="00">
<INPUT type="button" id="setAlarm" name="setAlarm" value=" alarm ON " onClick="changeFlg();">
★
 </div>
</FORM>
</BODY>
</HTML>

Categories

Resources