iosvideoyoutubeyoutube-javascript-api

How can I trigger a YouTube video to play in browser on iOS by clicking on a play button instead of the embed?


On my site, I want to have users watch an embedded YouTube video without leaving the page, but I don't want to have the not so stylistic YouTube embed visible prior to clicking.

This is entirely doable on desktop, as you can use the YouTube JavaScript API to trigger the embed to play, but on iOS, programmatic triggering of the player to play is blocked. So how can I do this on iOS?


Solution

  • When thinking about this problem, I thought that one alternative route would be to have a layer that's opaque and styled, but you could click through it. This would mean the user thinks they're clicking a pretty button, when actually they're just clicking the embed to play.

    Turns out there's a way of doing this, using the fancy (unofficial) CSS pointer-events property! Setting this to none means that clicks don't register, and instead punch straight through the element to whatever is behind it. In this case, the YouTube embed iframe. Support is iOS 6+.

    Here's a JSFiddle of it working.

    Note this is for iOS (and maybe Android) - it utilises the behaviour in which the video will automatically go full screen when it starts playing. If you watch this on desktop, the overlay remains.. overlaid.

    There's some more polishing to be done with this to get it schmick:

    You could do some tricky stuff with this technique, e.g. having a small player iframe overlaid by a small button. Still going to go fullscreen, so it'll work fine.

    But regardless, there you go - proof of concept of playing a YouTube video on iOS without the user knowing they clicked on an embed.