Autoplay videos when finished

Asked

Viewed 58 times

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 clicking, it changes the src videos by those who have data-id-iframe.

I’m also using the YouTube Player API Reference for iframe Embeds that I need for when the video ends, it switch to the next on the list.

The problem is that it works only on transferring the first video to the second, then does not give back.

Here is the script used.

In the code below is the code I use to change the src of iframe.

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 is executed when a list element is clicado and then he changes the src from iframe and runs 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 to assert, I show how the function of the Youtube API

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);
    }
  }

1 answer

0


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

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

This code will only capture the element data-id="2" 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>
        <script src="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>
<script src="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 worry about some things, but for our joy, there’s the method loadPlaylist, with this method we only need to pass a array with the IDs necessary and the API of Youtube will manage it for us, for example:

jQuery

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="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>
  • I used that case variables iframe and next return 0, which is what returns the first time, in the function of the first video.

  • When the video ends, you call muda_video(0, 0);. These values never change except if you click on the video.

  • The answer is correct! What helped me immensely was the loadVideoById, had no knowledge!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.