Autoplay of videos when finished

0

I have the following code

    <div class="col-lg-12" style="padding:40px 10px 40px 10px;">
      <div class="col-lg-1" style="padding-right:0;margin-top:20px;">
          <i class="fa fa-chevron-left fa-4x"></i>
      </div>
      <div class="col-lg-10" style="overflow:hidden;padding:0;">
          <div class="col-lg-2 list_altos selected_vid" data-id="1" data-id-iframe="ftWI2X_ORDI">
              <img src="http://img.youtube.com/vi/ftWI2X_ORDI/0.jpg"style="width:100%;">
          </div>
          <div class="col-lg-2 list_altos" data-id="2" data-id-iframe="m5JuhUOVIm8">
              <img src="http://img.youtube.com/vi/m5JuhUOVIm8/0.jpg"style="width:100%;">
          </div>
          <div class="col-lg-2 list_altos" data-id="3" data-id-iframe="HWeK1t9XsXk">
              <img src="http://img.youtube.com/vi/HWeK1t9XsXk/0.jpg"style="width:100%;">
          </div>
          <div class="col-lg-2 list_altos" data-id="4" data-id-iframe="hzvxahpw1lM">
              <img src="http://img.youtube.com/vi/hzvxahpw1lM/0.jpg"style="width:100%;">
          </div>
          <div class="col-lg-2 list_altos" data-id="5" data-id-iframe="4aUvwR87jLM">
              <img src="http://img.youtube.com/vi/4aUvwR87jLM/0.jpg"style="width:100%;">
          </div>
          <div class="col-lg-2 list_altos" data-id="6" data-id-iframe="C3oRqoBEOJY">
              <img src="http://img.youtube.com/vi/C3oRqoBEOJY/0.jpg"style="width:100%;">
          </div>
      </div>
      <div class="col-lg-1 text-right" style="padding-left:0;margin-top:20px;">
          <i class="fa fa-chevron-right fa-4x"></i>
      </div>
    </div>

Here I have a list of images that are videos that when clicked, it changes src of videos by those that have in data-id-iframe .

I'm also using the YouTube Player API Reference for iframe Embeds I need for when the video ends, it switches to the next one on the list.

The problem is that it works only on the transfer of the first video to the second, then does not go back.

Here is script used.

In the code below is the code that I use for the% change of% of src .

function muda_video(next, iframe){
        if(next == 0 || iframe == 0){
            next=2;
            iframe = $("div[data-id='2']").attr("data-id-iframe");
        }else{
            next=next+1;
        }
        $("#player_vid").attr("src", "https://www.youtube.com/embed/"+iframe+"?enablejsapi=1&autoplay=1")
        $(".selected_vid").removeClass("selected_vid");
        $("div[data-id='"+next+"']").addClass("selected_vid");
    }

In the code below it is executed when a list element is iframe and then it changes the clicado of the iframe and executes the video.

$(".list_altos").click(function(){
    var this_id=$(this).attr("data-id");
    var iframe = $(this).attr("data-id-iframe");
    muda_video(this_id, iframe);
    $(".selected_vid").removeClass("selected_vid");
    $(this).addClass("selected_vid");
});

And in the code ensure, I show how the function of src is structured

var tag = document.createElement('script');

  tag.src = "https://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_vid', {
      events: {
        'onStateChange': onPlayerStateChange
      }
    });

  }
  function onPlayerStateChange(event) {
    if(event.data === 0) {          
        muda_video(0, 0);
    }
  }
    
asked by anonymous 05.03.2018 / 20:16

1 answer

0

The video only runs the second, since you are using the code:

$("div[data-id='2']").attr("data-id-iframe");

This code will only capture the data-id="2" element and never the others. What you need to do is check the selected element and capture the next one, for example:

VanillaJS

<!DOCTYPE hml>
<html>
    <head>
        <title>Title of the document</title>
        <style>
            li { cursor:pointer; transition: margin-left .3s }
            li:hover { margin-left: 10px; }
            li.selected { font-weight:bold }

            @keyframes blink {
                25%  {opacity:0}
                50%  {opacity:1}
                75%  {opacity:0}
                100% {opacity:1}
            }
        </style>
    </head>

    <body>
        <div id="player"></div>

        <ol id="playlist">
            <li data-id-iframe="lB8ZsjMhy5M">AMY LEE - Speak To Me</li>
            <li data-id-iframe="dNoTvg0t52c">EPICA - Storm The Sorrow (OFFICIAL VIDEO)</li>
            <li data-id-iframe="Dys1_TuUmI4">Epica - Cry For The Moon</li>
            <li data-id-iframe="Rx9OoLwiAho">XANDRIA - Valentine</li>
            <li data-id-iframe="gGTAmmTiD_Y">XANDRIA - Nightfall</li>
            <li data-id-iframe="bpcNQZrhhKg">Nightwish - The Phantom Of The Opera</li>
        </ol>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><scriptsrc="https://www.youtube.com/iframe_api"></script>
        <script>
            /* Captura todos os elementos que contém o ID da música */
            const musics = document.querySelectorAll("[data-id-iframe]")

            let player;

            /**
             * Função de callback para quando o objeto
             * YT.Player for carregado
             */
            function onYouTubeIframeAPIReady() {

                /* Instancia o Player */
                player = new YT.Player('player', {
                    height: '360',
                    width: '640',
                    events: {
                        /**
                         * Adiciona um callback para ser executado 
                         * toda vez que o player sofrer uma alteração como:
                         *  - não iniciado
                         *  - encerrado
                         *  - em reprodução
                         *  - em pausa
                         *  - armazenando em buffer
                         *  - vídeo indicado
                         */
                        onStateChange: event => {

                            /* Verifica se o vídeo terminou a execução */
                            if (event.data == YT.PlayerState.ENDED) {

                                /* Captura a posição da música selecionada */
                                let index = [...musics].indexOf(document.querySelector("#playlist li.selected"));

                                /* Musica de música */
                                changeMusic( musics[index+1] )
                            }
                        }
                    }
                })
            }

            /* Adiciona evento de clique na playlist */
            musics.forEach( music => {
                music.addEventListener('click', changeMusic)
            })

            /*
             * Função para alteração da música
             * @param music MouseEvent|HTMLLiElement
             */
            function changeMusic(music) {

                /**
                 * Caso a variável music seja um MouseEvent,
                 * captura o valor de music.target. Caso contrário,
                 * captura o elemento passado pela variável
                 */
                music = music.target || music;

                /* Captura o ID do vídeo */
                player.loadVideoById( music.getAttribute("data-id-iframe") )

                /* Desmarca o vídeo selecionado */
                musics.forEach( el => el.classList.remove("selected") );

                /* Seleciona o vídeo atual */
                music.classList.add("selected")
            }
        </script>
    </body>
</html>

jQuery

<!-- -------------------------- -->
<!-- A mesma estrutura anterior -->
<!-- -------------------------- -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><scriptsrc="https://www.youtube.com/iframe_api"></script>
<script>
    /* Captura todos os elementos que contém o ID da música */
    const musics = $("[data-id-iframe]")

    let player;

    /**
     * Função de callback para quando o objeto
     * YT.Player for carregado
     */
    function onYouTubeIframeAPIReady() {

        /* Instancia o Player */
        player = new YT.Player('player', {
            height: '360',
            width: '640',
            events: {
                /**
                 * Adiciona um callback para ser executado 
                 * toda vez que o player sofrer uma alteração como:
                 *  - não iniciado
                 *  - encerrado
                 *  - em reprodução
                 *  - em pausa
                 *  - armazenando em buffer
                 *  - vídeo indicado
                 */
                onStateChange: event => {

                    /* Verifica se o vídeo terminou a execução */
                    if (event.data == YT.PlayerState.ENDED) {

                        /* Seleciona a próxima música */
                        changeMusic( $("#playlist li.selected").next() )
                    }
                }
            }
        })
    }

    /* Adiciona evento de clique na playlist */
    $(musics).click(function() {
        changeMusic($(this))
    })

    /*
     * Função para alteração da música
     * @param music MouseEvent|HTMLLiElement
     */
    function changeMusic(music) {

        /* Captura o ID do vídeo */
        player.loadVideoById( $(music).attr("data-id-iframe") )

        /* Desmarca o vídeo selecionado */
        $(musics).removeClass("selected");

        /* Seleciona o vídeo atual */
        $(music).addClass("selected");
    }
</script>

The problem is that you have to be concerned about some things, but to our delight, there is the loadPlaylist method, with this method we only need to pass array with the required IDs in YouTube API will handle this for us, for example:

jQuery

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><scriptsrc="https://www.youtube.com/iframe_api"></script>
<script>
    /* Captura todos os elementos que contém o ID da música */
    const musics = $("[data-id-iframe]")

    let player;

    /**
     * Função de callback para quando o objeto
     * YT.Player for carregado
     */
    function onYouTubeIframeAPIReady() {

        /* Instancia o Player */
        player = new YT.Player('player', {
            height: '360',
            width: '640',
            events: {
                onReady: function() {
                    let playlist = new Array();

                    $(musics).each(function() {
                        playlist.push( $(this).attr("data-id-iframe") );
                    })

                    player.loadPlaylist( playlist )
                },
                onStateChange: function(result) {
                    if (result.data == YT.PlayerState.PLAYING) {
                        $(musics).removeClass("selected")
                        $("[data-id-iframe=\""+player.getVideoData().video_id+"\"]").addClass("selected");
                    }
                }
            }
        })
    }

    /* Adiciona evento de clique na playlist */
    $(musics).click(function() {
        player.loadVideoById( $(this).attr('data-id-iframe') )
    })
</script>
    
06.03.2018 / 00:44