Kamran Arshad Kamran Arshad - 1 month ago 7
Javascript Question

JavaScript addEventListener() is not making call to the function

I'm new to JavaScript i just wrote some code that if a person writes his name in the input field the heading should pop-up and display his name with a hello message but its not making call to the function
Here is the code ...




<script type="text/javascript">
var name = document.getElementById("name");
var msg = document.getElementById("msg");

name.addEventListener("input", HelloMsg);

function HelloMsg(){
msg.innerHTML = "Hello " + name + "!";
}
</script>

Answer

You need to make sure that you don't scan the DOM for "name" until its been parsed into the DOM. This can be done by either moving your script so that it is below the HTML (just before the body tag closes) or set up another event handler that waits for the DOM to be built before looking for "name".

Next, you probably don't want the message written to the page to be "Hello " + name, since name is the textbox itself. You'd want the contents of the textbox via name.value.

  window.addEventListener("DOMContentLoaded", function(){

    var name = document.getElementById("name");
    var msg = document.getElementById("msg");

    name.addEventListener("input", HelloMsg);

    function HelloMsg(){
        msg.innerHTML = "Hello " + name.value + "!";
    }

    
  });
<input type="text" id="name"> <h1 id="msg"></h1>

Comments