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 Perform: Modifying Elements

Josh Slabaugh
Josh Slabaugh
9,635 Points

Does anybody know how to set an event handler to look for the 'ENTER' key instead of clicking on the buttons every time?

This list feels weird when using it, having to look for the little buttons every time I want to edit a task, add a new one... Does anyone have any advice on how to set the 'ENTER' key to add and edit tasks?

2 Answers

Steven Parker
Steven Parker
229,786 Points

A keypress generates an event just like a button click does. Just establish a handler for it:

document.getElementById("my_element_id").onkeypress = function(evt) {
  if (evt.which == 13) {  // 13 is ENTER
    // the ENTER key was pressed - do whatever you need here
  }
};

You just need to make an IF statement on your OnKeyPress event:

if(characterCode == 13)
{
    return false; // returning false will prevent the event from bubbling up.
}
else
{
    return true;
}

Code 13 means Enter.