Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Interactive Web Pages with JavaScript Traversing and Manipulating the DOM with JavaScript Perfect

Daniel Palkowski
Daniel Palkowski
7,439 Points

How could I also let the 'Enter' key do the same action as clicking the 'Add' button in the app?

Is there a simple way to add this method to the existing code?

2 Answers

Hi Daniel,

There's an easy way to do that. First, you add an event listener to your taskInput and have it listen for a keyboard event. I chose the keyup event. Pass in the event object placeholder to the anonymous function of the event listener; I named mine event for practical purposes but you can name it e or potato or whatever you choose. It's just important that there is a placeholder within the function to call upon. Next, you want to use the which property on this event object to see which keycode the user pressed. The number 13 is the keycode given to the Enter key on the standard keyboard. Check to see if that was the key pressed and if so, call the addTask() function! Bam!

//taskInput is the same as this: document.getElementById("new-task");
//add event listener for key up event and pass in event object
//event can be named anything you like although it's more intuitive 
//to use event or ev or e 
taskInput.addEventListener('keyup', function (event) {
  //check to see if the enter key was pressed
  if (event.which === 13) {
    //if so, run the addTask function
    addTask();
  }
});

You're very welcome! :) Happy Coding!