user3024235 user3024235 - 6 months ago 74
HTML Question

Add Youtube Subscribe Button using Javascript

I am attempting to add a youtube subscribe button dynamically to my site like so:

<script src="https://apis.google.com/js/platform.js"></script>
<div id="youtubeContainer"></div>
...
window.onload = function() {
document.getElementById("youtubeContainer").innerHTML = ('<div class="g-ytsubscribe" data-channel="GoogleDevelopers" data-layout="default" data-count="default"></div>');
}


But the button is not visible. I am wondering if there is a way to load a youtube subscribe button dynamically so I can enter a new channel name/id?

Answer

It is already working. I think problem in other code of your page.

<script src="https://apis.google.com/js/platform.js"></script>
<div id="youtubeContainer"></div>    
<script>

    document.getElementById("youtubeContainer").innerHTML = ('<div class="g-ytsubscribe" data-channel="GoogleDevelopers" data-layout="default" data-count="default"></div>');

</script>

JSBIN

[EDIT]

With window onload :

function renderYtSubscribeButton(channel) {
      var container = document.getElementById('youtubeContainer');
      var options = {
        'channel': channel,
        'layout': 'default'
      };
      gapi.ytsubscribe.render(container, options);
    }

window.onload = function() {
renderYtSubscribeButton("GoogleDevelopers");
}  

</script>

JSBIN

Comments