12

I have used a iframe video in my web page. This is my html code

<iframe id="video1" width="520" height="360" src="http://www.youtube.com/embed/TJ2X4dFhAC0?enablejsapi" frameborder="0" allowtransparency="true" allowfullscreen></iframe>
<a href="#" id="playvideo">Play video</a>

I need to play video onclick the play video link. How can i do that?

Sam Hanson
  • 1,317
  • 4
  • 22
  • 48

6 Answers6

29

This works, it appends autoplay=1 to the url causing the video to start playing.

addendum: If your video's source does not already have a querystring then it would be prudent to add a ? instead of a &, as is sometimes the case. This can be done by looking for its existence.

<iframe id="video1" width="520" height="360" src="http://www.youtube.com/embed/TJ2X4dFhAC0?enablejsapi" frameborder="0" allowtransparency="true" allowfullscreen></iframe>
<a href="#" id="playvideo">Play video</a>
<script>
 //use .one to ensure this only happens once
 $("#playvideo").one(function(){
  //as noted in addendum, check for querystring exitence
  var symbol = $("#video1")[0].src.indexOf("?") > -1 ? "&" : "?";
  //modify source to autoplay and start video
  $("#video1")[0].src += symbol + "autoplay=1";
 });
</script>

However, most people inherently understand that if they want a video to play, they will just click on it and I would suggest just leaving that to them or starting the video off with autoplay.

Also need to mention that autoplay does not work on mobile devices (powered by Android or iOS)

Travis J
  • 81,153
  • 41
  • 202
  • 273
  • It's working fine if i use you tube video. If i use any other like http://test.com/SF7Hg it's not working. – Sam Hanson Nov 29 '12 at 05:29
  • 5
    Naturally the code above wouldn't work on a video that isn't from Youtube ... it's code from the Youtube API. IF you want to user a video from somewhere else, you'd have to get an API from them (if one exists). In some cases, such as when the direct URL to the video source is public, you could embed it in your site as the source of an HTML5 video element and use the browser built-in API for HTML5 video playback. – jlmcdonald Nov 29 '12 at 06:14
  • This solution is still working perfectly fine right now – Gendrith Jul 15 '17 at 04:59
  • Might be worth mentioning that if there isn't already a parameter in the src of the video, I believe it should be "?autoplay=1", or at least that's what I needed, as @user_ivanp answered – Andrew Clavin Oct 10 '17 at 22:00
  • Perhaps if your url was lacking `?enablejsapi` as was included here in the example that would work. However, just adding that to an already existing querystring is problematic. See addendum. – Travis J Oct 10 '17 at 22:09
  • The only other thing I would recommend is adding a parameter to the function and preventing default so you can prevent the page from jumping to the top when the anchor is clicked: `function(e){ e.preventDefault(); }` – Smitty-Werben-Jager-Manjenson Aug 10 '20 at 20:14
  • Note that none of the solutions below appear to work on mobile browsers – Haydentech Oct 18 '21 at 20:01
  • How to do with only javascript? – huykon225 Dec 26 '21 at 04:18
7

I correctly set in end src - ?autoplay=1

   <iframe id="video1" width="450" height="280" src="http://www.youtube.com/embed/TJ2X4dFhAC0?enablejsapi" frameborder="0" allowtransparency="true" allowfullscreen></iframe>
    <a href="#" id="playvideo">Play button</a>
    <script>
     $("#playvideo").click(function(){
      $("#video1")[0].src += "?autoplay=1";
     });
    </script>
Ivan Pirus
  • 1,026
  • 11
  • 21
3

Here is another example. Check this here: https://codepen.io/rearmustak/pen/VXXOBr

const Player = document.getElementById('player2');
const PlayBtn = document.getElementById('play');
const stopBtn = document.getElementById('stop');
let times = 0, playY;
const playVideo = PlayBtn.addEventListener( 'click' , () => {
    if(times == 0){
      playY = Player.src += '?autoplay=1';
      times = 1;
    }
});

stopBtn.addEventListener( 'click' , () => {
    playY = playY.slice(0, -11);
    Player.src = playY
    times = 0;
});
.video-frame{
  overflow: hidden;
  margin-bottom: 10px;
}
button{
  border: none;
  background-color: #e75252;
  color: #ffffff;
  padding: 10px 15px;
  border-radius: 3px;
  cursor: pointer;
}
button:focus{
  outline: 0;
}
#stop{
  background-color: #ff0002;
}
<h1>Youtube video Play/Stop</h1>

<div class="video-frame">
  <iframe id="player2" width="560" height="315" src="https://www.youtube.com/embed/cs1e0fRyI18" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>

<button id="play">Play</button>
<button id="stop">Stop</button>
Enamul Haque
  • 144
  • 9
2

since the first answer is already 3 years old, let me point to the Youtube Player API. With that you can remote control your embedded player. See https://developers.google.com/youtube/iframe_api_reference?hl=en

With a small adjustment, you can start the video via link and without reloading the entire iframe:

<!DOCTYPE html>
<html>
  <body>
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
    <div id="player"></div>

    <!-- The Play-Link will appear in that div after the video was loaded -->
    <div id="play"></div>

    <script>
      // 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');

      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

      // 3. This function creates an <iframe> (and YouTube player)
      //    after the API code downloads.
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: 'M7lc1UVf-VE',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }

      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        //event.target.playVideo();
        document.getElementById('play').innerHTML = '<a href="#" onclick="play();">Play Video</a>';
      }

      function play(){
        player.playVideo();
      }

      // 5. The API calls this function when the player's state changes.
      //    The function indicates that when playing a video (state=1),
      //    the player should play for six seconds and then stop.
      var done = false;
      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
          setTimeout(stopVideo, 6000);
          done = true;
        }
      }
      function stopVideo() {
        player.stopVideo();
      }
    </script>
  </body>
</html>
Danny
  • 166
  • 1
  • 9
  • Doesn't work on Chrome. You get this error: `Untrusted origin: chrome-extension://boadgeojelhgndaghljhdicfkmllpafd` – Ozymandias Jan 07 '16 at 18:33
0

here is link to example http://jsfiddle.net/WYwv2/5/

Check out this

<!DOCTYPE html> 
<html> 
<body> 
<a href="#" id="playvideo" onclick="playme()">Play video</a>
    <iframe id="video1" width="520" height="360"  frameborder="0" ></iframe>
<script>
function playme() {
document.getElementById("video1").src = 'http://www.w3schools.com/tags/mov_bbb.mp4';
}
</script>
</body> 
</html>
​

We set the source of video dynamically.

ameya rote
  • 1,116
  • 1
  • 9
  • 13
0

it's work for me. please Check out this.

$("#player").on("pause", function(e) {
          clearTimeout(playTimeout);
      });
      var tag = document.createElement('script');
      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    
      var player;
        function onYouTubeIframeAPIReady() {
          player = new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'M7lc1UVf-VE',
            events: {
              'onReady': onPlayerReady,
              'onStateChange': onPlayerStateChange
            }
          });
        }
      function onPlayerReady(event) {
        event.target.playVideo();
          }
       var done = false;
        function onPlayerStateChange(event) {
          if (event.data == YT.PlayerState.PLAYING && !done) {
            setTimeout(stopVideo, 2000);//replace time here 
            $("#player").get(0).load();
            $("#player").get(0).pause();
            done = true;
          }
        }
        function stopVideo() {
          player.stopVideo();
        }
borchvm
  • 3,533
  • 16
  • 44
  • 45