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 keydown
event on the document
element, the player
variable is not set to anything.
Also jQuery normilizes the e.keyCode
and e.charCode
properties with e.which
but that is only if you bind to the event using jQuery:
$(document).on('keydown', function (event) {
var key = event.which,//get charCode of event
player = $('audio');//get the player (I'm assuming it's an `audio` tag)
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;
}
});
I noticed that trackId = $track.data('sc-track').id
probably isn't actually getting the ID of the $track
element, try one of these:
trackId = $track.data('sc-track')//this will get the `data-sc-track` attribute for this element
OR
trackId = $track[0].id//this will get the ID of this element
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