Search code examples
jqueryyoutube-apidom-eventssimplemodal

Popup window on youtube api event


I'm using simplemodal to popup a modal window. I've tested the modal window functionality and it is all working fine.

I have a hidden div element:

        <div id="form-box" class="form-box" style="display:none;">
        <div class="form-crop">
        <script type="text/javascript"         src="https://releasetechnique.infusionsoft.com/app/form/iframe/84f82828ea34c2a633bbe0a87560586c"></script>
        </div>
        </div>

this pops up just fine if as I tested it with a timer.

    <script type="text/javascript">
    $(function() {
    setInterval(update, 1000);
    });

    function update() {
    $("#form-box").modal();
    }
    </script>

Now what I'm trying to do is grab the information from Youtube's API, which I've successfully tested with the following:

    function onYouTubePlayerReady(playerId) {
        $ytplayer = document.getElementById("myytplayer");
        $ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
    }

    function onytplayerStateChange(newState) {
        alert("Player's new state: " + newState);


    }

This works as intended. It returns the current player state, and any time the player state is changed the alert lets me know.

Now, what I want to do is popup the modal window, when the player state is equal to 0. 0 means the player has stopped. So basically, 0 is returned as newstate once the Youtube video finishes playing.

I've tried the following and can't get it to work. Any suggestions?

    function onYouTubePlayerReady(playerId) {
        $ytplayer = document.getElementById("myytplayer");
        $ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
    }

    function onytplayerStateChange(newState) {
        if(newstate === 0) {
            $("#form-box").modal(); 
        }
    }

Solution

    1. $("form-box").modal(); should be $("#form-box").modal();
    2. Are you sure newState is a number? If not, you might want to use == instead of ===
    3. Remove other unused jQuery plugins in your page. They could be causing conflicts.