0

I am attempting to dynamically change the videoID of the YouTube API onclick. I have a list of items whose data src contains a YouTube URL. When a user clicks on a link, a modal pops up's playing that particular video. Once the video finishes, it redirects to another page.

If I hard code the ID, it works beautifully, but I cannot do that.

My only concern is I cannot get the videoID due to JavaScript scope. Is there anything you'd recommend I try?

    $(document.body).on('click', ".video-btn", function (e) {
        var $videoSrc = $(this).data("src");
        console.log($videoSrc);

        var **getVidID** = $videoSrc.substring(26);
        console.log(getVidID); 
    });

    var tag = document.createElement('script');
    tag.src = "//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', {
            playerVars: {
                'controls': 0
            },
            width: 1920,
            height: 1080,
            videoId: **getVidID,** I'd like to use the videoID here
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    };

    function onPlayerReady(event) {
        event.target.playVideo();
    };

    var done = false;
    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.ENDED && !done) {
            alert('Taking you to Review Material Now..')
            window.location.replace("http://www.google.com");
            done = true;
        }
    };
  • One option is to move the id variable to global scope, and then assign a value inside your function. Another option is to return the id from the function and assign it to a variable in the scope outside the function. – devlin carnate Apr 30 '20 at 22:07
  • @devlincarnate thank you for your response. I could return getVidID, but I am wondering how would I call the function outside the scope? Can you give me an example fo what that might look like? You don't have to use my example. –  Apr 30 '20 at 22:14
  • 1
    It's not clear what you're asking in that last comment. The variable won't be "outside the scope" if you return its value and assign it to a variable, nor will it be outside the scope if you use a global variable. Perhaps you need to update your post and show us where in your code you're wanting to use the id ? – devlin carnate Apr 30 '20 at 22:22
  • @devlincarnate no problem. Apologies for the confusion. I have a list of links that all contain a different URL to a YouTube video. When I click on the link, I get the ID, but I need to use it in the onYouTubeIframeAPIReady() function. You'll see exactly where in my edit. When I hard code the video ID, it works great, but I need it to be able to grab the ID when a user clicks on a link. It's been pretty tough to try to figure out. –  Apr 30 '20 at 22:30
  • Does this answer your question? [Access variable outside function scope](https://stackoverflow.com/questions/16942043/access-variable-outside-function-scope) – devlin carnate Apr 30 '20 at 22:36

1 Answers1

0

Here's one way to do it:

var getVidID; 
$(document.body).on('click', ".video-btn", function (e) {
    var $videoSrc = $(this).data("src");
    console.log($videoSrc);

    getVidID = $videoSrc.substring(26);
    console.log(getVidID); 
});

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

var player;
function onYouTubeIframeAPIReady() {
    console.log(getVidID);
    player = new YT.Player('player', {
        playerVars: {
            'controls': 0
        },
        width: 1920,
        height: 1080,
        videoId: **getVidID,** I'd like to use the videoID here
        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
        }
    });
};

Be aware: getVidID may not have a value, depending on where/when you call onYouTubeIframeAPIReady(). The click event function must run before it gets the id. So, you may want to validate that it has a value before you use it in that other function. Also, be aware that the value of that variable only changes when the click event fires...

devlin carnate
  • 8,309
  • 7
  • 48
  • 82
  • I think I understand, and I have coded it appropriately. It seems you're right, getVidID doesn't have a value but the ID gets console.logged from the first function so it does exist. I tried wrapping it with $(document).ready(function () { but still no luck. This one's tough, man haha –  Apr 30 '20 at 23:05