I have done a simple JS function and tried to call it with onload="updateClock()" but without any success. But if i change to onmouseenter="updateClock()" it works perfectly then I hover over with the mouse.
Why doesn't it work?
HTML:
<script src="clock.js" type="text/javascript"></script>
<section onload="updateClock();">
<span id="clock">00:00:00</span>
</section>
JS:
function updateClock(){
var currentTime = new Date ();
var hours = currentTime.getHours ();
var minuts = currentTime.getMinutes ();
var seconds = currentTime.getSeconds ();
//Pad with zeros
hours = (hours < 10 ? "0" : "") + hours;
minuts = (minuts < 10 ? "0" : "") + minuts;
seconds = (seconds <10 ? "0" : "") + seconds;
var time = hours + ":" + minuts + ":" + seconds;
document.getElementById("clock").innerHTML = time;
}
Only elements like iframe or img, in general, elements which can have content loaded from an external resource, have onload event. (And some DOM objects, like window ofcourse.)
A quick-fix would be to move the script tag after the section and use an IIFE:
<section>
<span id="clock">00:00:00</span>
</section>
<script src="clock.js" type="text/javascript"></script>
And in clock.js:
(function updateClock(){
:
}());
Related
I'm trying to make an updating JavaScript clock on my webpage. The problem I'm having is that, while the value itself updates (I use alert(timeNow) to show the value and make sure it's updating), the clock on the website doesn't. I was just wondering if there was something I was missing, or if I've just happened to come across something that I can't quite do. I'd prefer if there was a way to do it using jQuery, as I understand that a little better than normal JavaScript.
Javascript:
function updateClock() {
var thisDate = new Date();
if (thisDate.getHours() > 11 && thisDate.getHours() != 0) {
var Hours = Math.abs(thisDate.getHours() - 12);
var AmPm = "PM"
} else {
var Hours = thisDate.getHours()
var AmPm = "AM"
}
if (thisDate.getMinutes() < 10) {
var Mins = "0" + thisDate.getMinutes();
} else {
var Mins = thisDate.getMinutes();
};
var timeNow = thisDate.getDate() + "/" + (thisDate.getMonth() + 1) + "/" + thisDate.getFullYear() + " " + Hours + ":" + Mins + " " + AmPm;
return timeNow;
};
setInterval(updateClock, 1000);
$("span#time").append(updateClock());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="time"></span>
You are not consuming the return value of updateClock function, thus the updated time is not reflecting.
You should update the text of time span
Use
setInterval(function(){
$("span#time").text(updateClock());
}, 1000);
You are returning the time in the function updateClock(). What you actually want to do is to set it into the DOM at the end of updateClock(). Here is an updated example:
function updateClock() {
var thisDate = new Date();
if (thisDate.getHours() > 11 && thisDate.getHours() != 0) {
var Hours = Math.abs(thisDate.getHours() - 12);
var AmPm = "PM"
} else {
var Hours = thisDate.getHours()
var AmPm = "AM"
}
if (thisDate.getMinutes() < 10) {
var Mins = "0" + thisDate.getMinutes();
} else {
var Mins = thisDate.getMinutes();
};
var timeNow = thisDate.getDate() + "/" + (thisDate.getMonth()+1) + "/" + thisDate.getFullYear() + " " + Hours + ":" + Mins + " " + AmPm;
$("span#time").text(timeNow);
}
setInterval(updateClock, 1000);
You could of course also just use the returned value of updateClock() to update the DOM. In this way, you would separate the DOM manipulation and the JavaScript time calculation. #Satpal described this way.
Try This...
$(document).ready(function()
{
goforit();
});
var dayarray=new Array ("Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday")
var montharray=new Array("January","February","March","April","May","June",
"July","August","September","October","November","December")
function getthedate() {
d = new Date();
d.setUTCFullYear(2004);
d.setUTCMonth(1);
d.setUTCDate(29);
d.setUTCHours(2);
d.setUTCMinutes(45);
d.setUTCSeconds(26);
var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var hours=mydate.getHours()
var minutes=mydate.getMinutes()
var seconds=mydate.getSeconds()
var dn=""
if (hours>=12)
dn=""
if (hours>12){
hours=hours-12
}
if (hours==0)
hours=12
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds
//Hire change font size
var cdate=""
+ mydate.toLocaleString()
+""
if (document.all)
document.all.clock.innerHTML=cdate
else if (document.getElementById)
document.getElementById("clock").innerHTML=cdate
else
document.write(cdate)
}
if (!document.all&&!document.getElementById)
getthedate()
function goforit()
{
if (document.all||document.getElementById)
setInterval("getthedate()",1000)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<SPAN id=clock style="display:block"></SPAN>
setInterval(function() {
$("span#time").text(moment(new Date()).format('DD/M/YYYY LTS'));
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<span id="time"></span>
As my homework I have to prepare an asp webpage for database frontpage. To gain some extra points we can add a javascript. I deceided to add a clock I've found somewhere in script tutorials and modified it a little, but my skills are not enough to place it correctly
I want to place it in my MasterPage, but whole page dissapears only the clock lefts if I add it like this:
<div id="Zawartosc" onload="showTheTime();">
<%-- clock --%>
<script src="Script.js"></script>
</div>
and here is the clock script:
function showTheTime() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var ampm = "am";
var colon = '<IMG SRC="clock/colon.gif">';
if (hours < 10) hours = "0" + hours;
else hours = hours + '';
if (minutes < 10) minutes = "0" + minutes;
else minutes = minutes + '';
if (seconds < 10) seconds = "0" + seconds;
else seconds = seconds + '';
document.write('<IMG SRC="clock/' + hours.charAt(0) + '.gif">');
document.write('<IMG SRC="clock/' + hours.charAt(1) + '.gif">');
document.write(colon);
document.write('<IMG SRC="clock/' + minutes.charAt(0) + '.gif">');
document.write('<IMG SRC="clock/' + minutes.charAt(1) + '.gif">');
document.write(colon);
document.write('<IMG SRC="clock/' + seconds.charAt(0) + '.gif">');
document.write('<IMG SRC="clock/' + seconds.charAt(1) + '.gif">');
}
setTimeout("showTheTime()", 1000);
showTheTime();
could you please lead or help me to correct code and make the clock appear correctly with my page?
From w3schools.com
The write() method is mostly used for testing: If it is used after an
HTML document is fully loaded, it will delete all existing HTML.
Give this a try:
<div id="Zawartosc" onload="showTheTime();">
<script src="Script.js"></script>
</div>
function createElementImg(source) {
var img = document.createElement('img');
img.src = source;
return img;
}
function showTheTime() {
var clockEle = document.getElementById("Zawartosc");
while (clockEle.hasChildNodes()) {
clockEle.removeChild(clockEle.lastChild);
}
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var ampm = "am";
var colon = "clock/colon.gif";
if (hours < 10) hours = "0" + hours;
else hours = hours + '';
if (minutes < 10) minutes = "0" + minutes;
else minutes = minutes + '';
if (seconds < 10) seconds = "0" + seconds;
else seconds = seconds + '';
clockEle.appendChild(createElementImg("clock/' + hours.charAt(0) + '.gif"));
clockEle.appendChild(createElementImg("clock/' + hours.charAt(1) + '.gif"));
clockEle.appendChild(createElementImg(colon));
clockEle.appendChild(createElementImg("clock/' + minutes.charAt(0) + '.gif"));
clockEle.appendChild(createElementImg("clock/' + minutes.charAt(1) + '.gif"));
clockEle.appendChild(createElementImg(colon));
clockEle.appendChild(createElementImg("clock/' + seconds.charAt(0) + '.gif"));
clockEle.appendChild(createElementImg("clock/' + seconds.charAt(1) + '.gif"));
}
setTimeout("showTheTime()", 1000);
showTheTime();
is there possible to loop javascript function id? I have a form and the form is create using for loop; so I using this autosave javascript to save a draft; now the javascript only run the $("#remark1"). So I need to use for loop to loop the $("#remark1").
<script type="text/javascript">
$(function() {
if (localStorage) {
var content = localStorage.getItem("autoSave");
if(content) {
$("#remark1").text(content);
}
}
$("#remark1").autoSave(function() {
var time = showTime();
$("#msg").text("Draft Autosaved " + time).show();
}, 2000);
$("#refresh").click(function() {
location.reload();
});
$("#clear").click(function() {
localStorage.clear();
location.reload();
});
function showTime() {
var timeNow = new Date();
var hours = timeNow.getHours();
var minutes = timeNow.getMinutes();
var seconds = timeNow.getSeconds();
var timeString = "" + ((hours > 12) ? hours - 12 : hours);
timeString += ((minutes < 10) ? ":0" : ":") + minutes;
timeString += ((seconds < 10) ? ":0" : ":") + seconds;
timeString += (hours >= 12) ? " P.M." : " A.M.";
return timeString;
}
});
I want to loop ("remark1"), any kind solution?
Do you mean something like this?
function dynamicSave( id ) {
$("#" + id).autoSave(function() {
var time = showTime();
$("#msg").text("Draft Autosaved " + time).show();
}, 2000);
}
var ids = [ 'remark1', 'remark2' ];
ids.each(function(id) {
dynamicSave( id );
});
I have a JavaScript code to get new time. But when i reload the page the time doesn't change instead it says 1/10/2014 10:57, how can i add a function for the time and date to detect and change
Below is the code I tried but its not working.
<script type="text/javascript">
(function () {
// using current UTC time from server as ref, display local time in div id="now"
var now = new Date();
now.setTime(1389322677492);
var nowstr = ""
+ (now.getMonth() + 1) + "/"
+ now.getDate() + "/"
+ ((now.getYear() < 1000) ? now.getYear() + 1900 : now.getYear()) + " "
+ now.getHours() + ":"
+ ((now.getMinutes() < 10) ? '0' + now.getMinutes() : now.getMinutes());
var el = document.getElementById("now");
el.appendChild(document.createTextNode(nowstr));
})();
</script>
Thanks for helping me.
Thats because you are explicitly setting it to 1389322677492 everytime. All you need to do is remove the line:
now.setTime(1389322677492);
I want to display the system time on my jsp page. How can i do it? I'm trying this but only date is getting displayed that and not the time. It's all working fine in Internet Explorer but not in other browsers.
<td colspan="1" height="4" align="left" width="260" >
<font class="welcome1">
<strong>
<script language="JavaScript" src="js/date.js"></script>
<span id="clock">
<script language="JavaScript"
src="js/digitalClock.js"></script>
</span>
</strong>
</font>
</td>
Displaying the time on a web-page using js should be trivial .
new Date().toLocaleString() // displays date and time
new Date().toLocaleDateString() // displays date
new Date().toLocaleTimeString() // displays time
To display time you can use Date.
<html>
<head>
<script type="text/javascript">
<!--
function updateTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
if (minutes < 10){
minutes = "0" + minutes;
}
if (seconds < 10){
seconds = "0" + seconds;
}
var v = hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
v+="PM";
} else {
v+="AM"
}
setTimeout("updateTime()",1000);
document.getElementById('time').innerHTML=v;
}
updateTime();
//-->
</script>
</head>
<body>
<h4>Current Time: <span id="time" /></h4>
</body>
</html>
I've tested it in firefox and chrome. Found on this site.
Edit: time now gets updated every second.
You should read the documentation about the Date object in JavaScript (Date). It would be easier if you post the JS source.
/* set Date */
function tick() {
/* Get date in epoch */
var epoch = Date.now();
document.querySelector("#epoch").innerHTML = epoch;
/* Separate epoch */
var datetime = new Date(epoch);
var year = datetime.getFullYear();
var month = datetime.getMonth() + 1; // (0-11)
var date = datetime.getDate();
var hour = datetime.getHours();
var minute = datetime.getMinutes();
var second = datetime.getSeconds();
document.querySelector("#datetime").innerHTML =
year + "-" + addZero(month) + "-" + addZero(date) + " " +
addZero(hour) + ":" + addZero(minute) + ":" + addZero(second);
}
// Add 0 if argument < 10
function addZero(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
/* Call tick in interval 1 second */
setInterval(tick, 1000);
<p id="epoch"></p>
<p id="datetime"></p>
This seems the easiest solution, which uses setInterval with two arguments, the first being a callback, the second the interval in ms:
setInterval(function(){
document.write(new Date().toLocaleTimeString();
},1000);
So my solution should be the accepted answer because it is a real time.
For Date You can use below Javascript. Time will display in a text box. You can modify as per your requirement.
<html>
<head>
<script type="text/javascript">
var timer = null
function stop()
{
clearTimeout(timer)
}
function start()
{
var time = new Date()
var hours = time.getHours()
var minutes = time.getMinutes()
var seconds = time.getSeconds()
var clock = hours + ":" + minutes + ":" + seconds
document.forms[0].display.value = clock
timer = setTimeout("start()",1000)
}
</script>
</head>
<body onload="start()" onunload="stop()">
<form>
<input type="text" name="display" size="20">
</form>
</body>
</html>