2

The 1 and 3 are id of button and v1 and v3 are id of iframe(youtube emmbedded). i have already used a simple .show() and .hide() but the audio remained of hidden iframe so i am using .remove() and .show(). when i use .remove() the other iframe is gone completely and only iframe remains is of that button which i pressed which i want. however when i press button 3 the removed iframe is not able to load, is there a way to reload it?

the iframes i am using are :-

<iframe width="560" height="315" id="v1" src="https://www.youtube.com/embed/xGRjCa49C6U?modestbranding=1&controls=0&autoplay=1&loop=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" ></iframe>

<iframe width="560" height="315" id="v3" src="https://www.youtube.com/embed/9V9wr1AaIxY?modestbranding=1&controls=0&autoplay=1&loop=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" ></iframe>

and this is the js:-

$(function(){

  $('#1').on('click',function(){
    $('#v1').show();
        var getframe = document.getElementById("v3");
       getframe.remove();

  });

  $('#3').on('click',function(){
    $('#v3').show();
var getframe = document.getElementById("v1");
       getframe.remove();

  });

});

1 Answers1

1

Remove() method removes the element from the dom and its hard to reload.

So this can be done like the following.

  • Load YouTube iFrame API:-
<script src="https://www.youtube.com/iframe_api"></script> 
  • Create two different players that references the existing iFrames
$(function(){
window.YT.ready(function() {
var player1 = new YT.Player('v1');
var player3 = new YT.Player('v3');

$('#1').on('click',function(){
    $('#v1').show();
    player1.unMute();
    
    $('#v3').hide();
    player3.mute();
  });

  $('#3').on('click',function(){
    $('#v3').show();
    player3.unMute();
    
    $('#v1').hide();
    player1.mute();
  });
});
});

Demo

Hope this helps

Amal
  • 3,398
  • 1
  • 12
  • 20