1

I am making a simple encoder/decoder for me and my friend to talk to each other in code, or at least it should be simple. I keep getting the error "Unable to get property 'value' of undefined or null reference" when I try to reference any of my elements. I feel like I am doing something really dumb that is simple to fix, but I can't see it.

I have looked at several related questions already and have been trying a bunch of stuff that has been suggested, but nothing seems to work. By the way, I am using Microsoft Edge if that makes a difference.

var inMsg = document.getElementById("input")
var outMsg = document.getElementById("output")

document.addEventListener('keypress', (event) => {
  if (event.key == 'Enter') {
    try {
      event.preventDefault()
    } catch (e) {
      console.log(e)
    }
    try {
      console.log(inMsg.value)

    } catch (e) {
      console.log(e)
    }
  }
})
<html>

<head>
  <script src="./main.js" type="text/javascript"></script>
  <style>

  </style>
</head>

<body>
  <div>
    <h2>Paste Coded Message Here -></h2>
    <textarea id="input" value=""></textarea>

    <textarea id="output"></textarea>
  </div>
</body>

</html>

Usually I am able to just log the value no problem, but it says the element is null when I console.log it.

Nazim Kerimbekov
  • 3,965
  • 6
  • 23
  • 48
JellyFox
  • 35
  • 1
  • 1
  • 6
  • 2
    When is your script run? It it run after the page is done rendering, or might it run before then? What happens if you look up the elements inside the event listener instead of earlier? – Alex Broadwin May 11 '19 at 20:07
  • put your script tag at the end of the document, that will work for now... For details see: https://stackoverflow.com/questions/436411/where-should-i-put-script-tags-in-html-markup – Axel M May 11 '19 at 20:10
  • As an alternative to what @AxelM said you can use DOMContentLoaded event: https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event – Walk May 11 '19 at 20:12

2 Answers2

0

Try adding defer to your script tag like so:

<script src="./main.js" type="text/javascript" defer></script>

I believe the html parser hasn't reached your inMsg element by the time the script is executed and so the value of the element is undefined.

Let me know if that works!

Nazim Kerimbekov
  • 3,965
  • 6
  • 23
  • 48
mepley
  • 411
  • 3
  • 14
  • Glad to help! Basically, html is read top to bottom and ` – mepley May 11 '19 at 20:34
0

Move the first two lines into the add event listener function. This function might called before the dom is ready and isMag variable filled with null.