Play next video automatically

Asked

Viewed 591 times

0

I want to make a local application that plays the videos selected by the user through the checkbox, and as soon as a video is finished, the other begins.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Videos</title>
</head>
<body>

    <input type="checkbox" id="pacotei" name="Pacote" value="Pacote i">
    <label for="pacotei">CAPSULA</label>
    <br>
    <input type="checkbox" id="pacoteii" name="Pacote" value="Pacote ii">
    <label for="pacoteii">CREME</label>
    <br>
    <input type="checkbox" id="pacoteiii" name="Pacote" value="Pacote iii">
    <label for="pacoteiii">SACHE</label>
    <br>
    <button onClick="show()"> Mostrar vídeo </button>   

    <div id="videoDiv" style="display: none">

        <video id="video" width="600" height="auto" autoplay loop>
            <source id="source" src="" type="video/mp4">
        </video>
    </div>


    <script type="text/javascript">
        function show(){   
            let pacote = document.querySelector('[name="Pacote"]:checked')
            let source = document.querySelector('#source')

            if(pacote.value === 'Pacote i')
            {
                source.setAttribute('src', './video1.mp4')


            }
            else if(pacote.value === 'Pacote ii') {
                source.setAttribute('src', './video2.mp4')
            }
            else if(pacote.value === 'Pacote iii') {
                source.setAttribute('src', './video3.mp4')
            }

            document.querySelector('#videoDiv').style.display = 'block'
            document.querySelector('#video').load()
        }
    </script>
</body>
</html>

1 answer

1


You need the event onended of the video element to know when the video ended and be able to run the next one. Some changes to your code are needed, such as removing the attribute loop video tag, function use querySelectorAll instead of just querySelector to select the checked checkboxes (in the first can be returned more than one match, in the second only one match), and a few more adaptations to make it work. Check out in the example:

<html>
<head>
<meta charset="utf8">
<meta content-type="text/html">
</head>
<body>
    <input type="checkbox" id="pacotei" name="Pacote" value="Pacote i">
    <label for="pacotei">CAPSULA</label>
    <br>
    <input type="checkbox" id="pacoteii" name="Pacote" value="Pacote ii">
    <label for="pacoteii">CREME</label>
    <br>
    <input type="checkbox" id="pacoteiii" name="Pacote" value="Pacote iii">
    <label for="pacoteiii">SACHE</label>
    <br>
    <button onClick="show()"> Mostrar vídeo </button>   

    <div id="videoDiv" style="display: none">

        <video id="video" width="600" height="auto" autoplay controls>
            <source id="source" src="" type="video/mp4">
        </video>
    </div>


    <script type="text/javascript">
        function show(){   
            //para selecionar uma ou mais checkboxes, use querySelectAll
            //será retornado um nodelist, similar a um array, com todos
            //os cehckbox que foram selecionados pelo usuario, veja com //console.log(pacotes);
            //pequena mudanca no nome da variavel
            let pacotes = document.querySelectorAll('[name="Pacote"]:checked')
		
            let source = document.querySelector('#source')
	    //nesse array vão ser colocados os videos que devem ser tocados
	    let videos = [];

	    //Nesse trecho você indica quais videos devem ser adicionados ao array
	    //Como deve ser adicionado mais de um, você não deveria usar if/else if
            //pacotes[0] é a sua primeira checkbox, pacotes[1] a segunda, pacotes[i] a enesima checkbox
            if(pacotes[0].value === 'Pacote i')
            {
                videos.push('./video1.mp4');

            }
            if(pacotes[1].value === 'Pacote ii') {
                videos.push('./video2.mp4');
            }
            if(pacotes[2].value === 'Pacote iii') {
                videos.push('./video3.mp4');
            }


            document.querySelector('#videoDiv').style.display = 'block'
	
	    //agora você precisa carregar o primeiro video (se houver)
	    if(videos.length > 0){
                let video_indice = 0;
                let video = document.querySelector('#video');
                //seta o atributo src do video primeiro video video_indice = 0
                source.setAttribute('src', videos[video_indice]);              
	        video.load()

                //nesse ponto você deve usar o evento onended no elemento #video
	        //que é disparado quando o video termina de rodar
                video.addEventListener('ended', function(){
                    video_indice++;
                    //tocara até o ultimo indice do array videos
                    if(video_indice < videos.length){
                        source.setAttribute('src', videos[video_indice]);              
	                video.load();                        
                    }
                });
            }
            
        }
    </script>

</body>
</html>

A better approach would be to insert the video sources into the attribute value of checkboxes, avoiding having to indicate later what should be in the value of every checkbox. Something like this:

<html>
<head>
<meta charset="utf8">
<meta content-type="text/html">
</head>
<body>
    <input type="checkbox" id="pacotei" name="Pacote" value="./video1.mp4">
    <label for="pacotei">CAPSULA</label>
    <br>
    <input type="checkbox" id="pacoteii" name="Pacote" value="./video2.mp4">
    <label for="pacoteii">CREME</label>
    <br>
    <input type="checkbox" id="pacoteiii" name="Pacote" value="./video3.mp4">
    <label for="pacoteiii">SACHE</label>
    <br>
    <button onClick="show()"> Mostrar vídeo </button>   

    <div id="videoDiv" style="display: none">

        <video id="video" width="600" height="auto" autoplay controls>
            <source id="source" src="" type="video/mp4">
        </video>
    </div>


    <script type="text/javascript">
        function show(){   
            //para selecionar uma ou mais checkboxes, use querySelectAll
            //será retornado um nodelist, similar a um array, com todos
            //os cehckbox que foram selecionados pelo usuario, veja com //console.log(pacotes);
            //pequena mudanca no nome da variavel
            let pacotes = document.querySelectorAll('[name="Pacote"]:checked')
		
            let source = document.querySelector('#source');


            document.querySelector('#videoDiv').style.display = 'block'
	
	    //agora você precisa carregar o primeiro video (se houver) 
            //a partir do nodelist pacotes
	    if(pacotes.length > 0){
                let pacote_indice = 0;
                let video = document.querySelector('#video');
                //seta o atributo src do primeiro video 
                //primeiro indice do nodelist, obtido a partir do atributo value
                source.setAttribute('src', pacotes[pacote_indice].value);              
	        video.load()

                //nesse ponto você deve usar o evento onended no elemento #video
	        //que é disparado quando o video termina de rodar
                video.addEventListener('ended', function(){
                    pacote_indice++;
                    //tocara até o ultimo indice do array pacotes
                    if(pacote_indice < pacotes.length){
                        source.setAttribute('src', pacotes[pacote_indice].value);              
	                video.load();                        
                    }
                });
            }
            
        }
    </script>

</body>
</html>

  • Buddy.. thank you very much.. you and sinister.. now I’m going to work in the application style.. I’m going to win a promotion at the company.. the idea and present in a tv the production work of these pharmaceutical items..

  • Amigo.. juven_v can help me with something ? can I put a text to appear before each video ? but this text has to be related to the choice of video.. example.. if choose capsule and cream video.. before each video I need to put a text with a few sentences saying that the person chose capsula and a text with a few phrases saying that they chose cream.. help me. I have no idea how to do.. until the program creates a nodelist but not knowing how to access the nodelist and pass events.

Browser other questions tagged

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