Reputation: 15
I have this video tag with flash fallback:
<video id="myvideo" width="480" height="224" autoplay preload="auto" loop poster="intro6.jpg">
<source src="intro6.mp4" type="video/mp4">
<source src="intro6.webm" type="video/webm">
<source src="intro6.ogv" type="video/ogg">
<object width="480" height="224" type="application/x-shockwave-flash" data="player.swf">
<param name="movie" value="player.swf" />
<param name="flashvars" value="autostart=true&controlbar=hide&image=intro6.jpg&file=intro6.mp4&repeat=always" />
<img src="intro6.jpg" width="480" height="224" />
</object>
</video>
And as you can see i do not have any controls, it's just a looping video that autoplays. This works great on desktop browsers, but not so much on Android and iOS. So i need the controls to be visible on Android as it doesnt autoplay or loop. And on iOS i need the video not to autoplay.
Is there a way to accomplish this with javascript? And keep in mind i don't know much javascript.
Thanks!
Upvotes: 1
Views: 4807
Reputation: 7853
Probably the easiest and most practical way is to check the user agent to see if you're on Android.
if (navigator.userAgent.indexOf('Android') >=0) {
document.getElementById('myvideo').controls = true;
}
In general, user agent sniffing is "frowned upon". It's usually best to use feature detection, since some far future version of the Android browser might support autoplay. But mobile browsers aren't usually very good at telling you when they don't support the video/audio spec.
Another way to do it is to check for events. In FF/Chrome/IE9+, the event will fire a series of events, including: loadstart
, progress
, durationchange
, etc... up to play
and playing
. In the Android browser (at least, the old-ish version that I have), the video will instead fire a stalled
event. You could look for stalled
and then enable the controls. You could remove them again when you get the 'play' event.
var video = document.getElementById('myvideo'), started = false;
if (video && video.addEventListener) { //in case of IE < 9
video.addEventListener('stalled', function() {
if (!started) video.controls = true;
}, false);
video.addEventListener('play', function() {
started = true;
video.controls = false;
}, false);
}
But there are other reasons why you might see that event, like a slow internet connection. So you'll still risk seeing the controls for a bit in a desktop browser until the video starts.
You don't need to worry about iOS. It won't autoplay, even if you want it to.
Upvotes: 3