After refreshing the iframe, the OnStateChange function fails to work properly

My iframe is set up to play videos within a specific time range but I'm encountering an issue. When the end time is reached (case 0), I want to reload a slightly different URL (with autoplay=0).

The problem arises when OnStateChange doesn't recognize any changes after the first refresh of the iframe. Consequently, it fails to reload after the second viewing and instead starts playing the video from the beginning on the third view. How can I ensure that the video reloaded every time it reaches the end time?

I've also checked out this query on Stack Overflow, though I couldn't find a solution there – although it might hold the key?

(It may seem like an unconventional approach, but this is what works best for my current situation.)

On another note, I'm struggling to change the id="player" to ytplayer instead. Is it not meant to be modified?

<html>
<head>
<script type="text/javascript" src="http://www.youtube.com/player_api"> </script>
<script>
var player;
// This function creates an <iframe> (and YouTube player)
// after the API code downloads.
function onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
        events: {
            'onStateChange': function (event) {
                switch (event.data) {
                    case -1:
                        console.log ('unstarted');
                        break;
                    case 0:
                        console.log ('ended');
                        var iframe = document.getElementById('player');
                            //autoplay=0
                            iframe.src = "http://www.youtube.com/embed/TINASKjjNfw?&enablejsapi=1&controls=1&showinfo=1&start=20&end=25&rel=0&autoplay=0"
                        console.log ('player reloaded');                        
                        break;
                    case 1:
                        console.log ('playing');
                        break;
                    case 2:
                        console.log ('paused');
                        break;
                    case 3:
                        console.log ('buffering');
                        break;
                    case 5:
                        console.log ('video cued');
                        break;
                }
            }
        }
    });
}
</script>
</head>
<body>

    <iframe class="video-frame" id="player" width="560" height="315" 
    src="http://www.youtube.com/embed/TINASKjjNfw?&enablejsapi=1&controls=1&showinfo=1&start=20&end=25&rel=0&autoplay=1"
    frameborder="0"></iframe>
</body>
</html>

Update: I attempted the following code snippet as suggested in this post, but unfortunately, it didn't yield the desired results.

<script>
function floaded1() {

player1 = new YT.Player('player1', {
        events: {
            'onStateChange': function (event) {
if (event.data == 0) {
                        var iframe = document.getElementById('player1');
                            iframe.src = "http://www.youtube.com/embed/TINASKjjNfw?&enablejsapi=1&controls=1&showinfo=1&start=20&end=25&rel=0&autoplay=0" //autoplay=0
};
            }
        }
    });
}    </script>

    </head>
<body>

<iframe onload="floaded1()" id="player1" width="240" height="220" 
src="http://www.youtube.com/embed/0Bmhjf0rKe8
?enablejsapi=1&rel=0&showinfo=2&iv_load_policy=3&modestbranding=1&start=10&end=15&rel=0&autoplay=1" 
frameborder="0" allowfullscreen> </iframe>

Answer №1

I discovered a successful solution and wanted to share it in case anyone else might find it helpful.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://www.youtube.com/player_api"> </script>
</head>
<body>
<script>
function onEndReload() {
    ytplayer = new YT.Player('ytplayer', {
        events: {
            'onStateChange': function (event) {
                if (event.data == 0) {
                        var iframe = document.getElementById('ytplayer');
                            //use iframe.src = iframe.src if you want to reload the url in the iframe, if not – se below;
                            iframe.src = "http://www.youtube.com/embed/M7lc1UVf-VE?&enablejsapi=1&controls=1&showinfo=1&start=20&end=25&rel=0&autoplay=0"
                            onEndReload();
                            console.log ('player reloaded'); 
                };
            }
        }
    });
}
</script>
<iframe onload="onEndReload()" id="ytplayer" name="ytplayeriframe" width="560" height="315" src="http://www.youtube.com/embed/M7lc1UVf-VE?&enablejsapi=1&controls=1&showinfo=1&start=20&end=25&rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to hide a button on this virtual keyboard after it has been clicked?

After creating a virtual keyboard using HTML and CSS, I am looking to implement JavaScript code that will hide a button after it is clicked. Here is the code I have tried so far: function hideButton() { var button = document.getElementById("simple_butto ...

Bootstrap's square-shaped columns

I would like to implement a grid of squares for navigation purposes. By squares, I mean that the colored areas should have equal width and height. Currently, I have achieved this using JavaScript, but I am interested in a CSS-only solution. My project is ...

How can I make a function visible in function expressions when it's currently not showing up?

Here's a function expression that I have: var inputChecker = function(field) { return function() { if(field === '' || field === 'undefined' || field === null) { return false; } return true; ...

Troubleshooting a Custom Menu Control in HTML

Would you mind taking a look at the menu I have set up in this fiddle: http://jsfiddle.net/Gk_999/mtfhptwo/3 (function ($) { $.fn.menumaker = function (options) { var cssmenu = $(this), settings = $.extend({ title: "Menu", ...

Insert JavaScript into this HTML document

I am looking to integrate the "TimeCircles JavaScript library into my project, but I am facing some challenges in doing it correctly. I plan to include the necessary files at the following location: /js/count-down/timecircles.css and /js/count-down/timecir ...

Find the item in the pop-up window

When removing a user from my list, a JavaScript popup pops up prompting to confirm the action with two buttons "OK" / "Annuler" : https://i.sstatic.net/BEdH2.png Is there a way to use Selenium to find and interact with these buttons? ...

Storing numbers with a thousand separator in a JavaScript Array: tips and tricks

I need to save an Array in this format const price = [ 1.000, 24.500, 3.99, 4.00 ]; However, when I use console.log to print it, the numbers get truncated to integers (1 instead of 1.000, and 4 instead of 4.00). What's the best way to preserve the ...

Can I stream a file from an external server in NodeJS without routing it through my own server?

My website provides links for downloading or streaming media files from another server. Currently, my setup looks something like this: download = (req, res) -> song_id = req.params.id download_url = "http://mediaserver.com/#{song_id}" console.log ...

Ways to merge multiple cells horizontally in a table right from the beginning

Is there a way to start the colspan from the second column (Name)? See image below for reference: https://i.stack.imgur.com/RvX92.png <table width="100%"> <thead style="background-color: lightgray;"> <tr> <td style="width ...

Javascript error: Function not defined

For some reason, I seem to be hitting a roadblock with this basic function. It's telling me there's a reference error because apparently "isEven" is undefined: var isEven = function(number) { if (number % 2 == 0) { return true; ...

What is the best way to navigate to the top of a form panel?

I'm currently developing a Sencha Touch mobile app. I have a form panel with multiple fields, so I made it scrollable. However, every time I open the screen (panel), scroll down, navigate to other screens, and then return to the form panel, it stays s ...

Checkbox paired with a read-only text column

I have a simple HTML input field with JavaScript functionality, which includes a checkbox. I am trying to write text in the input field when the checkbox is checked, and make the input field read-only when it is not checked. Can anyone provide an example ...

Using JavaScript/TypeScript to sort through and separate two arrays

Creating a list of checkboxes on a UI allows users to toggle and filter data results. To achieve this, I am storing the selected checkboxes as a string array. The structure of my code is outlined below: export interface IMyObjectFromAPI { status: { ...

Trouble arising from PHP's encoded array

I am encountering an issue with retrieving a value from PHP and passing it to Javascript. The PHP array is encoded like this : echo json_encode($myArray); On the Javascript side, I use the following code within the $.ajax method: success:function (data) ...

Progress Bar Countdown Timer

I have made some progress on my project so far: http://jsfiddle.net/BgEtE/ My goal is to achieve a design similar to this: I am in need of a progress bar like the one displayed on that site, as well as the ability to show the days remaining. Additionally ...

Reading very large .csv files using the FileReader API in JavaScript with only HTML/jQuery can be accomplished by following these

Having trouble handling a large .csv file over 40 MB (with more than 20,000 lines) and displaying it as an HTML table. I'm developing a system using only pure HTML + JQuery. This is the format of my .csv worksheet: ================================== ...

Implement the same reference functionality in a React Function component that is seen in a React Class component

Is it possible to replicate the same functionality of class component ref in a function component? Here's an example: const AnotherComponent = () => { const DoSomething = () => console.log(something); return <div> There is some co ...

Unlocking JSON data with identical keys using JavaScriptLearn how to access JSON data with

I need help converting my JSON training data that includes classes and sentences into a different format. [ { class: 'Reservation', sentence: 'make reservation' }, { class: 'Reservation', sentence: 'do reservation&a ...

Adjusting window size when page is resized

While browsing through SO, I stumbled upon this interesting piece of code: var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], x = w.innerWidth || e.clientWidth || g.clientWidth, y = w. ...

Creating a dynamic path to an imported file in React: A step-by-step guide

Struggling with a dilemma regarding dynamically generated paths for importing files in React. I have utilized the map() function to generate a dynamic part of the code, consisting of a repetitive sequence of div elements, each housing an audio element. The ...