Paramasivan
Paramasivan

Reputation: 39

Autoplay youtube video on hover/mouseover

I am trying to play the youtube video for auto play when the iframe tag is on focus. Tried the following but it is not working. Error with my jquery? I want to add &autoplay=1 to the src of iframe when it is focus.

Html :-

<div class="vid-wrapper" >
    <iframe width="100%" height="100%" id="video1" src="https://www.youtube.com/embed/bxgorUGjCIw?rel=0" frameborder="0" allowfullscreen scrolling="auto" ></iframe>
</div>

Css :-

.vid-wrapper{
width: 100%;
position: relative;
padding-bottom: 56.25%;
height: 0;
z-index:-20;
}
.vid-wrapper video, .vid-wrapper iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index:-1;
}

Jquery :-

$(document).ready(function() {
 $("#video1").mouseenter(function(){

  $(this).attr("src",$(this).attr("src") + "&amp;autoplay=1");
 });

$("#video1").mouseleave(function(){
  var src= $(this).attr("src");
  var arr_str = src.split("&amp;");
  $(this).attr("src",arr_str[0]);
  });
});

Any help? Thanks in advance.

Upvotes: 1

Views: 9434

Answers (1)

Dekel
Dekel

Reputation: 62576

Actually you don't really want to change the src attribute, but to use youtube's api for that:

The snippet will not work due to cross-origin problems (specifically in stackoverflow) but the code works.

var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    height: '390',
    width: '640',
    videoId: 'M4Xrh8OP1Jk'
  });
}

$(document).on('mouseover', '#player', function() {
  player.playVideo();
});
$(document).on('mouseout', '#player', function() {
  player.pauseVideo();
});
<script src="//www.youtube.com/player_api"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="player"></div>

Here is a working jsfiddle:
https://jsfiddle.net/rurc8rb9/

Upvotes: 2

Related Questions