Not really sure how to title this, but that's the best I could come up with.
I've created a music player in the browser for my own personal use (so there's no emphasis on cross-browser or anything like that). It all works dandy except I am having issues when pressing the space bar.
Currently songs are listed on the page based on a search criteria. Each song has a play/pause button that reflects what the current state is. When the button is clicked it executes the appropriate command to the player (.play() or .pause()). I have also added in some jQuery code so when the space bar is pressed, it acts like I am clicking the corresponding button. Up to this everything works correctly. The space bar fails however in one very specific scenario: If I click the play/pause button and then press the space bar without clicking or doing anything else, it sends two "click"/"press" commands to player, effectively creating a stutter effect since the player is now pausing and then immediately playing, or playing and then immediately pausing. I have viewed the "double" click in the Firebug console.
I have searched quite a bit online but have found nothing relevant. To be clear, I am already hiding the player's controls by omitting the "controls" attribute. However I have tried troubleshooting with them present, and I think I am onto something. By default Firefox (and it would seem other browsers, as this issue does exist in both Chrome and IE11) allows you to play and pause the audio with the space bar if you are focused on the player. And I think that's the kicker: When the .play() or .pause() function executes, it appears as though it inherently gives focus to the audio element, even though this focus doesn't seem to be loggable by Firebug.
I have tried a couple rudimentary things to try to "counteract" this inherent focusing such as triggering a focus or click event on other elements on the page, but it doesn't seem to make any difference.
Perhaps most importantly... by adding .preventDefault() to the event doesn't stop the audio element from being controlled by the keyboard. In other words, without trying to do anything else, if I tell the event to test for the space bar and to prevent default, if I click on the audio element (when it has the controls attribute since it's then visible) and then press the space bar it will play or pause the song. I can't seem to find anyway to stop this.
Does anyone have any insight into this? Thanks for reading!