开发者

start/play embedded (iframe) youtube-video on click of an image

I'm trying to start playing an embedded youtube video by clicking an image. The idea is to have an image on top of a video, and when the image is clicked it fades out and starts playing the video.

I'm using jquery to fade the image, and was hoping to find a way to play or click the video using jquery as well.

The fad开发者_StackOverflowing is working fine, but I can't figure out how to trigger the video to play. I got it to work on a couple of browsers by setting the video to autoplay and hide it, and then fade in the video when the image was clicked. On most browsers the video would autoplay when faded in, but in chrome it started to autoplay even when it was hidden. It didn't work well in iOS either.

Since I'm pretty new at this, I'm not even sure if I'm writing it 100% correct, but I've tried something like this without success:

     $('#IMAGE').click(function() { $('#VIDEO').play(); });

So, how would I go about to make the video play on an image click? Is there a way to play the video when the image is clicked, just using jquery?

Thank you in advance.


The quick and dirty way is to simply swap out the iframe with one that has autoplay=1 set using jQuery.

THE HTML

Placeholder:

<div id="videoContainer">
  <iframe width="450" height="283" src="https://www.youtube.com/embed/VIDEO_ID_HERE?wmode=transparent" frameborder="0" allowfullscreen wmode="Opaque"></iframe>
</div>

Autoplay link:

<a class="introVid" href="#video">Watch the video</a></p>


THE JQUERY

The onClick catcher that calls the function

jQuery('a.introVid').click(function(){
  autoPlayVideo('VIDEO_ID_HERE','450','283');
});

The function

/*--------------------------------
  Swap video with autoplay video
---------------------------------*/

function autoPlayVideo(vcode, width, height){
  "use strict";
  $("#videoContainer").html('<iframe width="'+width+'" height="'+height+'" src="https://www.youtube.com/embed/'+vcode+'?autoplay=1&loop=1&rel=0&wmode=transparent" frameborder="0" allowfullscreen wmode="Opaque"></iframe>');
}


You can do this simply like this

$('#image_id').click(function() {
  $("#some_id iframe").attr('src', $("#some_id iframe", parent).attr('src') + '?autoplay=1'); 
});

where image_id is your image id you are clicking and some_id is id of div in which iframe is also you can use iframe id directly.


To start video

var videoURL = $('#playerID').prop('src');
videoURL += "&autoplay=1";
$('#playerID').prop('src',videoURL);

To stop video

var videoURL = $('#playerID').prop('src');
videoURL = videoURL.replace("&autoplay=1", "");
$('#playerID').prop('src','');
$('#playerID').prop('src',videoURL);

You may want to replace "&autoplay=1" with "?autoplay=1" incase there are no additional parameters

works for both vimeo and youtube on FF & Chrome


Example youtube iframe

<iframe id="video" src="https://www.youtube.com/embed/xNM7jEHgzg4" frameborder="0"></iframe>

The click to play HTML element

<div class="videoplay">Play</div> 

jQuery code to play the Video

$('.videoplay').on('click', function() {
    $("#video")[0].src += "?autoplay=1";
});

Thanks to https://codepen.io/martinwolf/pen/dyLAC


You are supposed to be able to specify a domain that is safe for scripting. the api document mentions "As an extra security measure, you should also include the origin parameter to the URL" http://code.google.com/apis/youtube/iframe_api_reference.html src="http://www.youtube.com/embed/J---aiyznGQ?enablejsapi=1&origin=mydomain.com" would be the src of your iframe.

however it is not very well documented. I am trying something similar right now.


Html Code:-

<a href="#" id="playerID">Play</a>
<iframe src="https://www.youtube.com/embed/videoID" class="embed-responsive-item" data-play="0" id="VdoID" ></iframe>

Jquery Code:-

$('#playerID').click(function(){
    var videoURL = $('#VdoID').attr('src'),
    dataplay = $('#VdoID').attr('data-play');

    //for check autoplay
    //if not set autoplay=1
    if(dataplay == 0 ){
        $('#VdoID').attr('src',videoURL+'?autoplay=1');
        $('#VdoID').attr('data-play',1);
     }
     else{
        var videoURL = $('#VdoID').attr('src');
        videoURL = videoURL.replace("?autoplay=1", "");
        $('#VdoID').prop('src','');
        $('#VdoID').prop('src',videoURL);

        $('#VdoID').attr('data-play',0);
     }

});

Thats It!


You can work with this one.
The image will be on top of the video div. If you click on the image then the video will appear and will start playing.
This works on desktop and also responsive devices also. Adding ?autoplay=1 at the end of the video URL does not auto play the video on the mobile device. But this solution work on every devices.
Note: This may not work after running the code in stackoverflow but works fine on local or production site.

var $ = window.jQuery;
      $('.custom-svg-container').click(function (ev) {
            $(`<div id="custom-youtube-video"></div>
            <script> 
                var tag = document.createElement('script');
                tag.src = "https://www.youtube.com/player_api";
                var firstScriptTag = document.getElementsByTagName('script')[0];
                firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
                var player;

                function onPlayerReady(event) {
                    event.target.mute();
                    event.target.playVideo();
                }

                function onYouTubePlayerAPIReady() {
                    var id = 'i810CxN5Q6Q';
                    player = new YT.Player('custom-youtube-video', {
                        width: "560",
                        height: "349",
                        videoId: id,
                        playerVars: {
                            // 'playsinline': 1,
                            // 'autoplay': 1,
                            // 'mute': 1,
                            // 'controls': 0,
                            // "playlist": id,
                            // 'loop': 1
                        },
                        events: {
                            'onReady': onPlayerReady,
                        }
                    });
                }

            <\/script>`).appendTo($('.custom-iframe-container'))

            setTimeout(function() {
                $('.custom-benefit-image').addClass('showVideo')
            }, 10)
            // $('#custom-youtube-video')[0].src.includes("?autoplay=1&mute=1") ? "" : $('#custom-youtube-video')[0].src+= "?autoplay=1&mute=1";
            // ev.preventDefault();
        });
div.taskboard-container { 
        margin: auto;
        border: solid; 
        border-radius: 18px;
        border-width: 15px; 
        background: #000000; 
    }
                        
    .custom-iframe-container { 
        display: none;
        position: relative; 
        width: 100%; 
        padding-bottom: 65%;
        height: 0; 
        justify-content: center; 
        align-items: center;
        border: solid; 
        border-radius: 18px;
        border-width: 15px;
        background: #000000;
    }

    .custom-benefit-image.showVideo .custom-iframe-container { 
        display: flex;
    }

    .custom-benefit-image.showVideo .custom-svg-container { 
        display: none 
    }

    .custom-benefit-image.showVideo .taskboard-container { 
        display: none 
    }
                        
    .custom-benefit-image .custom-svg-container { 
        position: absolute; 
        height: 100%; 
        width: 100%; 
        display: flex; 
        justify-content: center;
        align-items: center; 
        z-index: 9999;
        cursor: pointer; 
    }
                        
    .custom-benefit-image .custom-svg-div {
        width: 12%;
        height: auto;
    }

    .custom-iframe-container iframe{
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      padding: 0;
      margin: 0;
    }
<html>
  <head>
      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
<body>
  <!-- 1. The <iframe> (video player) will replace this <div> tag. -->
  <div class='custom-benefit-image' style="height: 700px; width: 700px; position: relative;">
      <div class='custom-svg-container'>
          <div class='custom-svg-div'>
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"
              "><!-- Font Awesome Pro 5.15.4 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) --><path d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm115.7 272l-176 101c-15.8 8.8-35.7-2.5-35.7-21V152c0-18.4 19.8-29.8 35.7-21l176 107c16.4 9.2 16.4 32.9 0 42z"></path></svg>
          </div>
      </div>

      <div class='custom-iframe-container'> 
        
      </div>   

      <div class='taskboard-container' style="height: 700px; width: 700px;"> 
          <img width="100%" height="100%" src='https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510__480.jpg' > 
      </div> 
  </div>

</body>
</html>


This should work perfect just copy this div code

<div onclick="thevid=document.getElementById('thevideo'); thevid.style.display='block'; this.style.display='none'">
<img style="cursor: pointer;" alt="" src="http://oi59.tinypic.com/33trpyo.jpg" />
</div>
<div id="thevideo" style="display: none;">
<embed width="631" height="466" type="application/x-shockwave-flash" src="https://www.youtube.com/v/26EpwxkU5js?version=3&amp;hl=en_US&amp;autoplay=1" allowFullScreen="true" allowscriptaccess="always" allowfullscreen="true" />
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜