Why is the location of this script changing the behaviour of webpage? [duplicate]

Use a document.ready function.

When you put the code before closing the body tag, the DOM has been completely created. Different case when you put it inside the head tag


Scripts located within the head are executed before the body has been rendered. So the elements you're trying to target don't exist yet.


Try wrapping js referencing element within window.onload event handler where js is within head element; as the #submit element is not loaded into DOM when .addEventListener attached to document.getElementById("submit")

<html>

<head>
  <title>key events</title>
  <script>
    window.onload = function() {
      document.getElementById("submit").addEventListener("click", eve);

      function eve() {
        var uname = document.getElementById("uname").value;
        uname = uname.toUpperCase();
        document.getElementById("uname").value = uname;
      }
    }
  </script>
</head>

<body>
  <input type="text" id="uname" length="20" />
  <br />
  <input type="submit" id="submit" value="submit" />

</body>

</html>