1

The I trying to change video id 8IYzyTYucKQ to WKV_z36pVAk dynamically but it is not changing.

I think the library bellow only work on page reload so when I clicked the button the new Id changes but the video play the older Id, when I reload the video again Id reset to default one.

<!DOCTYPE html> 
    <html> 
    <head> 
    <meta charset="utf-8" /> 
    <title>About</title>
         <script type="text/javascript">
          function val1(val)
          {
        location.reload();
        document.getElementsByTagName("div")[0].setAttribute("data-video", val);
            //document.getElementById("youtube-audio").data-video=val;
            //document.getElementById("p1").innerHTML=val;
            alert(val);


          }

         </script>
    </head> 
    <body> 
    <h3 style="color:#0066dd">Hello</h3>

    <center>


    <div data-video="8IYzyTYucKQ"
         data-autoplay="0"
         data-loop="1"
         id="youtube-audio">
    </div> 

    </center>
    <button onclick="val1('WKV_z36pVAk')">change</button>


    </body> 
    <script src="https://www.youtube.com/iframe_api"></script>
    <script src="https://cdn.rawgit.com/labnol/files/master/yt.js"></script>
    </html>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
VyTcdc
  • 986
  • 10
  • 32

1 Answers1

1

You're reloading the page after you change the data attribute using :

location.reload();

What returns the attribute to the default value when the page refreshed and ready again.

Simple example using the API :

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://www.youtube.com/iframe_api"></script>
  </head> 
  <body>
    <h3 style="color:#0066dd">Hello</h3>
    <button id="change_video">change</button>
    <div id="player"></div>

    <script>
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '360',
          width: '640',
          videoId: 'M7lc1UVf-VE'
        });
      }

      $('#change_video').on('click', function(){
        player.loadVideoById('WKV_z36pVAk');
      })
    </script>

  </body>
</html>

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • Hi I put the question please check it the link : https://stackoverflow.com/questions/45571141/i-want-to-dynamically-change-the-video-id-from-youtube-but-it-is-not-working – VyTcdc Aug 08 '17 at 14:32