The addEventListener returns an error when I use it on the name object

advertisements
<input type="text" id="name" />

<script>
    var name = document.getElementById("name");

    name.addEventListener("focus",select,false);

    function select() {
      console.log("Focused!");
    }
</script>

I created a variable called name in the global scope and selected the nameId element. Then I called addEventListener on the object but it returned as undefined method.


You don't have an element with the ID "name", so btn evaluates to undefined. Undefined has no method addEventListener

You will need to use document.getElementById('btn')

it appears name is reserved in javascript, I know name is a keyword in a lot of other languages. Change your code to this and it works

var nme = document.getElementById("nameId");
var email = document.getElementById("emailId");
var submit = document.getElementById("submit");

if(window.addEventListener) {
    nme.addEventListener("focus",select,false);//This is where I get the error
    nme.addEventListener("blur",deselect,false);
    email.addEventListener("focus",select,false);
    email.addEventListener("blur",deselect,false);
    submit.addEventListener("press",validate,false);
} else {
    nme.attachEvent("onfocus",select);
    nme.attachEvent("onblur",deselect);
    email.attachEvent("onfocus",select);
    email.attachEvent("onblur",deselect);
    submit.attachEvent("onpress",validate);
}