I’m trying to put the current time in an HTML and Javascript project

Asked

Viewed 75 times

0

function carregar(){
var msg = window.Document.getElementById('msg')
var foto = window.Document.getElementById('foto')
var date = new Date()
var hora = data.getHours()
msg.innerHTMl = `Agora sao ${hora} horas`
}

and calling in HTML

<body onload='carregar()'>
  • Yeah, but where’s the problem ?

  • The page was to appear the time and does not appear already tested the call of js with an Alert and working, the codes perish this with the correct syntax but does not appear the time

  • 1

    Could be that: Document this with the D in capital letters should be document, msg.innerHTMl the L this in minuscule should be msg.innerHTML

  • I switched here but nothing has changed, I’m taking a course on youtube my code is the same as the teacher’s but you’re not going... I’d have another way to put the hours beyond that??

2 answers

1


There are a number of problems in your code that makes the time is not inserted in your element. First of all, to get the document elements, you must use document instead of Document.

Also, on the line where you receive the time you use a variable called data instead of the variable date that you created to receive the Date instance.

The third problem with your code is that you used innerHTML with the lowercase "l". See below the correction of your code:

function carregar(){
    var msg = document.getElementById('msg');
    var foto = document.getElementById('foto');

    var date = new Date();
    var hora = date.getHours();

    msg.innerHTML = `Agora sao ${hora} horas`;
}

NOTE: It is not mandatory to use semicolons (;) in Javascript, but it is recommended to avoid some bugs that may occur. Also, it is a good practice to make the code (in my opinion) more beautiful and standardized in a certain way.

  • Vlw brother thank you very much was to an hr in this already

0

Anderson, all right?

Apparently in your Javascript code there is a small error:

var date = new Date();
var hora = data.getHours();

In the above script, you declared a variable that has not been declared, which is the case of the date, the compiler is trying to recognize some variable but it is not possible, you need that date to become the variable you declared earlier.

var hora = date.getHours();

In this case, you will be able to use the getHours method because the variable date is the type Date.

To conclude, you have assembled a string that will be shown inside an HTML element that has the id #msg, programming languages usually recognize a string (phrase) using double or single quotes string = "sua frase aqui"; or string = 'sua frase ${aqui} com alguma variável;

I believe that with these tips, you can follow your online learning.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.