I have made a bit of research, but not get any result. This is the situation. I have an html file and a javascript file. The html is:
<html>
<head>
<script src="js/calculateRemainigTime.js"></script>
<script>
reservationTime();
</script>
</head>
<body>
<button onclick = "reservationTime()">Start</button>
<p id="demo">Result Here</p>
</body>
The javascript file is:
function reservationTime()
{
var date = new Date();
var currHour = date.getHours()
var x = document.getElementById("demo");
x.innerHTML = "The example time is: " + currHour;
}
The problem is that when I press the Start button, the text of the "p" tag with id = "demo" does not change. Thanks!
3 Answers 3
In your JS file you have:
var x = document.getElementById("demo");
The problem is the element with "demo" as the id does not yet exist in the DOM when your JS file is loaded. Browsers start executing JS the moment it's loaded and evaluated. And if you put the JS file in your head, then it's doing this before the browser knows about any of the elements in your body.
You can either listen for the DOMContentLoaded event instructing the browser to execute your JS after the DOM has loaded, or move the JS from the head to the end of the body.
1 Comment
You don't need this:
<script>
reservationTime();
</script>
Comments
Try this code:
<html>
<head>
<script>
function reservationTime(testVersion){
var date = new Date();
var currh = date.getHours();
var currm = date.getMinutes();
var currs= date.getSeconds();
var x = document.getElementById("demo");
x.innerHTML = "The example time is: " +
currh + " hours, " + currm + " minutes and " +
currs + " seconds. The test version is: " + testVersion;
}
reservationTime('pre');
</script>
</head>
<body>
<button onclick = "reservationTime('click')">Start</button>
<p id="demo">Result Here</p>
<script>
reservationTime('post');
</script>
</body>
Some things to note:
I added a variable 'testVersion' to the function, then I call it in three places, on page load you will see the code with the 'post' note, if you comment out the post line (Put // at the start of the line) you will not see any change, this is because when the 'pre' line of code is read the #demo tag does not exist in the DOM (it gets created as it works through the code from top to bottom) The on click should work, I added seconds so you can see a change every time you click.
Once you confirm the code is working move it back into the external file, You can use a browser tool like chromes Developer tools to make sure the page was loaded (it should come up as a 404 if the file cant be found).
scriptto the end of yourbody<script src="calculateRemainigTime.js"></script>