1

I have a div with an img and an iframe video. I want to play the video just after click over the image. (its not valid change url for ux purposes)

My js code is not working as expected. The youtube video does not start.

$(".youtube-video img").click(function (e) { 
  $(".youtube-video .video").trigger('click');
    ev.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div class="youtube-video">
    <img src="http://i.ytimg.com/vi/<?php echo $video1 ?>/maxresdefault.jpg">
    <div class="video">
        <iframe frameborder="0" src="https://www.youtube.com/embed/<?php echo $video1 ?>" allowfullscreen="" style=""></iframe>
    </div>
</div>
Ali Esmailpor
  • 1,209
  • 3
  • 11
  • 22
Jose
  • 117
  • 1
  • 8
  • what do you mean by *js code is not working as expected..* please elaborate ? – Swati Feb 07 '21 at 12:11
  • @Swati I dont know why, but the youtube video doesnt start – Jose Feb 07 '21 at 12:19
  • 1
    here `$(".youtube-video. img")` remove that extra dot before image . Also , check [this](https://stackoverflow.com/questions/6246939/start-play-embedded-iframe-youtube-video-on-click-of-an-image) post. – Swati Feb 07 '21 at 12:26
  • Its edited. Its not working. – Jose Feb 07 '21 at 12:30
  • did you check that link which i have added in my previous comment ? – Swati Feb 07 '21 at 12:39
  • Does this answer your question? [play iframe video on click a link javascript](https://stackoverflow.com/questions/13619074/play-iframe-video-on-click-a-link-javascript) – skobaljic Feb 07 '21 at 12:40

1 Answers1

0

Use player.playVideo() with JQuery.

So it will be like that in javascript: document.querySelector("iframe").contentDocument.getElementsByClassName("html5-video-player")[0].playVideo()

The html5-video-player class is the class which contain the function playerVideo and we just get the iframe Dom with contentDocument.
And do not forget to add ?enablejsapi=1&version=3&playerapiid=ytplayer at the end of the iframe's link.

From the Youtube player api doc