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.


About keydown,

A wrap contain keys and audios

<div class="wrap">  
 <div class="keys">  
  <div data-key="65" class="key">  
  <span class="sound">clap</span>  
 <div data-key="83" class="key">  
  <span class="sound">hihat</span>  
 <audio data-key="65" src="sounds/clap.wav"></audio>  
 <audio data-key="83" src="sounds/hihat.wav"></audio>  

A. work fine

window.addEventListener ('keydown', function(e) {

B. it wont show anything...is it error ?

var wrap = document.querySelector ('.wrap');
wrap.addEventListener ('keydown', function(e) {

1 Answer

I think the reason it isn't working is that the keydown event for an element will only trigger IF the element has the focus. So an input field with the cursor in it would trigger that element's keydown event but would not trigger a different element's keydown event.

In your case, the focus would have to be inside the .wrap div for the keydown to work but there is nothing inside the div which can take the focus.

However, the document keydown event will always trigger. If there is not a good reason for the event to be on the element, I would attach it to the document.