2

The addEventListener on click is working but on event.keypress or event.code dont. I can't understand why? I tried to add key code, with and without "", tried to remove default, with indication of object length (inputLength() > 0 && event.code "Enter") etc.. still nothing. Can't find a solution in existent threads((.

var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");


function inputLength() {
    return input.value.length;
}

function createListElement() {
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(input.value));
    ul.appendChild(li);
    input.value = "";
}

button.addEventListener("click", function() {
    if (inputLength() > 0) {
        createListElement();
    }
})

button.addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.key === "Enter") {
        createListElement();
    }
})

4 Answers 4

3

Try changing "keyup" to "keypress":

button.addEventListener("keypress", function(event) {
    event.preventDefault();
    if (event.key === "Enter") {
        createListElement();
    }
})
Sign up to request clarification or add additional context in comments.

Comments

1

For addEventListener, you may need a third argument false e.g. button.addEventListener("click",function(){blah},false);

Comments

1
button.addEventListener("keyup", function(event) {
  // Number 13 is the "Enter" key on the keyboard
  if (event.key === 'Enter') {
    // Cancel the default action, if needed
    event.preventDefault();
    //now do what you want to do.
    createListElement();  
}
} false);

I just want to say, that you should definetly use google more often. I was able to find the anwser after 1 google search. Anyways hope this helps.

2 Comments

Thank you for such a quick answ. i tried it already, it dont work because event.keyCode is deprecated and how i mentioned before with other (event.keypress or event.code ) still dont work.
try event.key === 'Enter', and also do what the guy said above me, put false before the last bracket in the addEventListener.@m
0

I found the right way:

function addListAfterKeyPress(event) {
    if (inputLength() > 0 && event.key === "Enter") {
        createListElement();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.