Angus Dobson
Angus Dobson

Reputation: 41

How do you stop onload from repeating

I have the following code to replace the src of the iframe to have a random video each time the page is loaded. However the page just keeps loading and keeps running the function. How do I stop the function for repeating.

<div id="rightsugg"><iframe id="randomVideo" width="560" height="315" src="" onLoad="displayRandomVideo();" frameborder="0" allowfullscreen></iframe></div>
                    <script type="text/javascript">
                        function getRandomVideo() {
                            var videos = [
                                'https://www.youtube.com/embed/kiTO7c_qeZs',
                                'https://www.youtube.com/embed/z4Hfv00eqoI',
                                'https://www.youtube.com/embed/7cdZYQB5ONE',
                                'https://www.youtube.com/embed/i1gE3nyQnKg',
                            ];
                            var video = videos[Math.floor(Math.random()*videos.length)];

                            return video;
                        }

                        function displayRandomVideo() {
                            var htmlVideo = document.getElementById("randomVideo");
                            htmlVideo.src = getRandomVideo();
                        }
                        displayRandomVideo();
                    </script>

Upvotes: 0

Views: 1086

Answers (2)

madpoet
madpoet

Reputation: 1063

Why are you using onload event of the iframe in the first place?

$(window).load(displayRandomVideo);

would do it, and just remove the onload attribute in the <iframe> tag.

Upvotes: 0

kaze13
kaze13

Reputation: 309

Just unregister the onLoad event after the videa has been displayed.

function displayRandomVideo() {
        var htmlVideo = document.getElementById("randomVideo");
        htmlVideo.src = getRandomVideo();
        htmlVideo.onload=null;  
}

jsfiddle

Upvotes: 1

Related Questions