57

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 fading 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.

3

8 Answers 8

55

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>');
}
6
24

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.

2
  • 1
    what if the url has query params in it prior. food for thought.
    – jahrichie
    Aug 26, 2014 at 0:21
  • If you know it always there then you can replace ?autoplay=1 with &autoplay=1. But if this is uncertian then you have to find those params and append this additional one to that Sep 3, 2014 at 6:42
17

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

3
  • 3
    it's actually ?autoplay=1 instead of & Aug 12, 2015 at 2:50
  • 3
    @Mike that depends if there's any parameters in the source URL or not.
    – kano
    Apr 25, 2017 at 19:28
  • Easiest solution
    – Ravimallya
    Mar 2, 2023 at 5:35
11

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

5
  • @JohannCombrink And all solution will not work either as Android/iOS built-in behavior stackoverflow.com/a/15093243/248616
    – Nam G VU
    Sep 29, 2016 at 10:49
  • @alex This should be accepted answer as it cleanest code via .src += "&autoplay=1"
    – Nam G VU
    Sep 29, 2016 at 10:50
  • @NamGVU, since the original poster said in the description that with his original attempt "It didn't work well in iOS either" this tells me that he needs it to function on iOS. And since more browsing is done on mobile devices than desktop browsers, then this should NOT be accepted as the correct answer as it doesn't solve the ops issue. Is this what we do now is accept a partially working answer or should we be accepting a complete answer. hrrmmmm....I wonder.
    – agon024
    Oct 11, 2016 at 21:07
  • I was trying to do the same thing, but I already had ?rel=0 in my iframe. If you are in the same boat use "&autoplay=1" instead of "?autoplay=1" Oct 15, 2018 at 16:17
  • it is not play when click to button
    – huykon225
    Dec 25, 2021 at 7:20
4

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.

0
2

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!

1

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>

-2

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>

Not the answer you're looking for? Browse other questions tagged or ask your own question.