Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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!