I'm designing a webpage with several tiles. On desktop, hovering each tile will trigger jPlayer to start play a preview of music, the code to do this (with jQuery) is:
function init_tile(id, url) {
$(id).hover(
function() {
$('#player').jPlayer("setMedia", {mp3: url}).jPlayer("play");
},
function() {
$('#player').jPlayer("stop");
}
);
}
It worked pretty well except for Mobile Safari on iOS: jPlayer doesn't play audio file automatically in iPad , from which I learned that only a user action (click/tap but not 'hover' which, doesn't make sense on touch screens) could trigger HTML5 playback.
I liked the .hover
call because it worked extremely well on iPad. First quick tap will trigger the hover state, and then the second tap will follow the link. Tapping other tiles will restore previous hovered tiles. If I chose to simulate this using 'tap' event from jquery-mobile, it would be a lot of hassle.
I'm wondering what's the shortcut solution for this. I'm using the latest stable release for all dependencies.
Okay, I'll answer it myself.
It turned out that it's not too much of a hassle. Mobile Safari still sends mouseover/mouseout to the 'hot item' even when I don't use mouseover/mouseenter. I don't have to track tiles specifically.
I ended up with something like this:
if (Modernizr.touch) {
$(id).click(
function (e) {
if ($(id).hasClass('playing')) {
$(id).trigger('mouseout');
} else {
e.preventDefault();
$(id).addClass('playing');
$('#player').jPlayer("setMedia", {mp3: url}).jPlayer("play");
}
});
$(id).mouseout(
function () {
$(id).removeClass('playing');
$('#player').jPlayer("stop");
});
} else {
$(id).hover(
function () {
$('#player').jPlayer("setMedia", {mp3: url}).jPlayer("play");
},
function () {
$('#player').jPlayer("stop");
}
);
}
It used modernizr to detect touch device. This is basically a manual implementation of 'first tap to hover, second tap to follow' behavior. And you don't have to track hot tiles.