Zack Zack - 3 months ago 21
Javascript Question

Attaching keypress event handler

I have the following:

document.addEventListener('DOMContentLoaded', function(){
inputStyle();
});
function inputStyle(){
var noSpace = document.getElementsByClassName('noSpace');
noSpace = Array.prototype.slice.call(noSpace);
noSpace.forEach(function(el){
el.addEventListener('keypress', noSpaceInput(event));
});
}
function noSpaceInput(evt){
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 32) {
return false;
}
return true;
}


Basically, I want any
<input type="text" class="noSpace">
(input tags with class of noSpace to disallow a space character). I'm unable to attach the event handler with the code above, but if I attach the event handler in the markup instead, it works perfectly fine:

<input type="text" onkeypress="return noSpaceInput(event)">


Can someone explain?

Answer

You need to pass noSpaceInput, the function name. With parentheses, they supply the return value, which is problematic. addEventListener takes in a callback, not a boolean. Also, you need to use preventDefault to stop the event. Here's a snippet:

document.addEventListener('DOMContentLoaded', function(){
    inputStyle();
});

function inputStyle(){
    var noSpace = document.getElementsByClassName('noSpace');
    noSpace = Array.prototype.slice.call(noSpace);
    noSpace.forEach(function(el){
        el.addEventListener('keypress', noSpaceInput);
    });
}
function noSpaceInput(evt){
    evt = evt || window.event;
    var charCode = evt.which || evt.keyCode;
    if (charCode == 32) {
        evt.preventDefault();
    }
}
<input type="text" class="noSpace">
<input type="text" class="noSpace">
<input type="text" class="noSpace">

Notice how the event listener is added: el.addEventListener('keypress', noSpaceInput);. I also changed your ternary operators to || as they do the same thing.