dimanche 22 août 2021

Having YouTube play a random video from an array

How would I be able to have this work in the code?

or for this to be able to work in the code, would it be written differently?

var videos = [
    '0dgNc5S8cLI',
    'mnfmQe8Mv1g',
    'CHahce95B1g'
];

var index=Math.floor(Math.random() * videos.length);

How the code is set up is that, you click on the cover which opens a video.

https://jsfiddle.net/e4bg537p/

How would I be able to set it up so that it plays 1 random video from an array of YouTube ids?

That is what I am trying to figure out how to do.

Can someone show me how this would be done?

<div class="video video-frame" data-id="-SiGnAi845o"></div>

    (function manageCover() {

    function show(el) {
        el.classList.remove("hide");
    }

    function hide(el) {
        el.classList.add("hide");
    }

    function coverClickHandler(evt) {
        const cover = evt.currentTarget;
        hide(cover);
        const video = cover.parentElement.querySelector(".wrap");
        show(video);
    }

    const cover = document.querySelector(".jacket");
    cover.addEventListener("click", coverClickHandler);
}());

const videoPlayer = (function makeVideoPlayer() {

    let player = null;

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

    function onPlayerReady(event) {
        player = event.target;
        player.setVolume(100); // percent
    }

    function addPlayer(video) {

        const config = {
            height: 360,
            host: "https://www.youtube-nocookie.com",
            videoId: video.dataset.id,
            width: 640
        };
        config.playerVars = {
            autoplay: 0,
            cc_load_policy: 0,
            controls: 1,
            disablekb: 1,
            fs: 0,
            iv_load_policy: 3,
            rel: 0
        };
        config.events = {
            "onReady": onPlayerReady
        };
        player = new YT.Player(video, config);

    }

    function play() {
        player.playVideo();
    }
    return {
        addPlayer,
        play
    };
}());

function onYouTubeIframeAPIReady() {
    const cover = document.querySelector(".jacket");
    const wrapper = cover.parentElement;
    const frameContainer = wrapper.querySelector(".video");
    videoPlayer.addPlayer(frameContainer);
}

(function initCover() {

    function coverClickHandler() {
        videoPlayer.play();
    }

    const cover = document.querySelector(".jacket");
    cover.addEventListener("click", coverClickHandler);
}());



Aucun commentaire:

Enregistrer un commentaire