This a small portion of the javascript code I used for an HTML5 music player. I was wondering if you guys can help me build a HotKey to toggle the Play/Pause button using the Space key. Any ideas?
CODE:
$('.trackslist li').live('click', function(event) {
var $track = $(this),
$player = $track.closest('.player'),
trackId = $track.data('sc-track').id,
play = $player.is(':not(.playing)') || $track.is(':not(.active)');
if (play) { onPlay($player, trackId); }else{ onPause($player); }
$track.addClass('active').siblings('li').removeClass('active');
return false;
});
$('.next').live('click', function(event) {
$player = $(this).closest('.player');
onNext($player);
});
$('.prev').live('click', function(event) {
$player = $(this).closest('.player');
onPrev($player);
});
An idea I found:
document.onkeydown = function(e){
var ev = isIE?event:e;
if(ev.charCode && ev.charCode == 32)
player.playPause();
else{
switch(ev.keyCode){
case 32:
player.playPause();
break;
case 39:
player.nextSong();
break;
case 37:
player.prevSong();
break;
case 38:
player.volumeInc();
break;
case 40:
player.volumeDec();
break;
}
}
}
In your code for the
keydownevent on thedocumentelement, theplayervariable is not set to anything.Also jQuery normilizes the
e.keyCodeande.charCodeproperties withe.whichbut that is only if you bind to the event using jQuery:I noticed that
trackId = $track.data('sc-track').idprobably isn’t actually getting the ID of the$trackelement, try one of these:OR
One last note,
.live()has been depreciated as of jQuery 1.7. You should be using.delegate()if you are using an older version and.on()if you are using jQuery 1.7 or greater.Source: http://api.jquery.com/on