0

It has been discussed that autoplay is not working on mobile devices Apple as well as Android (Youtube autoplay not working on mobile devices with embedded HTML5 player).

However in order to not destroy my website performance I am only loading images and adding IFrames as soon as a user clicks as demonstrated by this tutorial (https://lean.codecomputerlove.com/make-your-own-lightweight-youtube-player/).

Essential idea is to add only HTML with the data attribute and image:

    <div class="video__youtube" data-youtube>
        <img src="https://i.ytimg.com/vi/VIDEO_ID/maxresdefault.jpg" class="video__placeholder" />
        <button class="video__button" data-youtube-button="https://www.youtube.com/embed/VIDEO_ID"></button>
    </div>

And later on add the IFrame via JavaScript as soon as the user clicks:

function createIframe(event) {
    var url = event.target.dataset.youtubeButton;
    var youtubePlaceholder = event.target.parentNode;

    var htmlString = '<div class="video__youtube"> <iframe class="video__iframe" src="' + url + '?autoplay=1" frameborder="0" allowfullscreen></iframe></div>';

    youtubePlaceholder.style.display = 'none';
    youtubePlaceholder.insertAdjacentHTML('beforebegin', htmlString);
    youtubePlaceholder.parentNode.removeChild(youtubePlaceholder);
}

However as Youtube autoplay does not work on mobile devices the user has to click two times for the same action which is inacceptable in terms of user experience. Therefore my idea is to trigger a click within the IFrame as soon as it is loaded (as the user already has clicked). Is there any possibility to achieve this?

Blackbam
  • 17,496
  • 26
  • 97
  • 150

1 Answers1

1

I'm not sure if it works when the back element is an iframe, but you can try the css pointer-events: none property.

Put the image covering the iframe, the click should go through the image and fire right on the iframe, then you could listen to some youtube callback to remove the image.

So, the iframe will be there from the beginning but covered with the image instead of inserting it after the image is clicked.

https://css-tricks.com/almanac/properties/p/pointer-events/ check this example, you click through a div in front of another.

arieljuod
  • 15,460
  • 2
  • 25
  • 36
  • Destroys a bit the purpose of what I want to achieve as this would mean the iframe must exist before the user clicks which is exactly what I want to avoid. However I might fake sth. with pointer-events:none; the idea is good. Still I wonder if it SHOULD work, as this would enable you to do evil thinks like stealing facebook likes for instance by having a click picture above a like button for instance. – Blackbam Aug 29 '18 at 14:35
  • Yeah, that's why I'm not sure it works with iframes on the back, it's just an idea to try. – arieljuod Aug 29 '18 at 14:45
  • Indeed it works: https://jsfiddle.net/rjtnpkh6/4/ . Thats pretty funny That allows you to do a lot of bad things – Blackbam Aug 29 '18 at 14:50