-1
<script>
document.getElementById("display").innerHTML = localStorage.getItem("notes");
function noteIt() {
localStorage.setItem("notes", localStorage.getItem("notes") + document.getElementById("txt").value + "<br>");
document.getElementById("display").innerHTML = localStorage.getItem("notes");
}
function reset() {
localStorage.setItem("notes", "")
document.getElementById("display").innerHTML = localStorage.getItem("notes");
}
</script>

<textarea id="txt"></textarea><br>
<button onClick="noteIt()">Note It!</button>
<button onClick="reset()">Reset!</button><br>
<p id="display"></p>

With this code, the problem is when I have data in the variable, "notes" when I reload the webpage the line at the top of the js won't run. If I typed in, "Hi" to the textarea and pressed "Note it!", when I reload the browser I do not see the text, "Hi" appear on my screen.

Could someone please help me? Thank you in advance!

  • Just for reference the page is rendered in order so it is generally a good idea to put all of your styles first (in the head), followed by all of your content, followed by you scripts. This way when items start rendering the styles are already ready and when the scripts start running the DOM is already established. – Marie May 04 '18 at 12:05

1 Answers1

-1

Yes, this happens because the <script> is before the elements you are targeting.

Browsers run JavaScript code as soon as they encounter the <script> tag. The p#display is not loaded when the code executes. That's why your code fails.

D. Pardal
  • 6,173
  • 1
  • 17
  • 37