Keep in mind that JavaScript is case sensitive , meaning it is case sensitive: a
is different from A
. Any character with the wrong case causes error (syntax, does not find an object etc).
Problems encountered:
1. function Relogio{
After the function name, you must follow the parentheses: function Relogio(){
2. relógio()
vs.. Relogio()
Note that in% w / o% of% w /% the function name is all lowercase, and the function name begins with a capital "R". Or you change one or the other so that they are both equal.
3. onload
The syntax is incorrect. The correct one is body
.
4. var data = new Data();
A case problem. JavaScript generally uses the camel case style when a property name or method is composed: Date()
+ var minutos = data.getminutes ();
= get
.
5. minutes
Same problem as the previous item.
6. getMinutes
Plus a case problem that causes syntax error. Remember var segundos = data.getseconds();
? The correct one is document.getElementByid("relogio").innerHTML
start with "i" uppercase: camel case
.
Only the element where you want to print the clock is missing. By% code%, it is assumed to be id
with document.getElementById
.innerHTML
. Enter it in div
:
<div id="relogio"></div>
If you want a timer so that the clock is not static, use id
(uninterrupted timer that performs a function in the interval stipulated in milliseconds).
As you are calling the function via #relogio
, in this case, you can put body
at the end of the setInterval()
function, like this:
setInterval(relogio, 1000); // 1000 = 1 segundo
Another important point (for beginners and experienced people) is the indentation of the code. A well-indented code makes it more readable and easy to maintain, especially in long codes ( learn more at this link ).
To study:
Fixed code:
function relogio(){
var data = new Date();
var horas = data.getHours();
var minutos = data.getMinutes ();
var segundos = data.getSeconds();
if (horas <10 ) {
horas= "0"+ horas;
}
if (minutos <10) {
minutos = "0"+ minutos;
}
if (segundos <10) {
minutos = "0"+segundos;
}
document.getElementById("relogio").innerHTML =horas+":"+minutos+":"+segundos;
setInterval(relogio, 1000);
}
<body onload="relogio();">
<div id="relogio"></div>
</body>
And finally: If you're using HTML5, you do not need to declare onload
in the script.