eegloo
eegloo

Reputation: 1499

How to load iframe on load using jquery?

Following is Function to embed youtube video in html. In this youtube video display on click but I want to do this on load using javascript. How can be done? Any help?

youtubeLoadVideos : function () {        
        // Find all the YouTube video embedded on a page
        var videos = document.getElementsByClassName("youtube"); 
        for (var i=0; i<videos.length; i++) {         
            var youtube = videos[i];

            // Attach an onclick event to the YouTube Thumbnail
            youtube.onclick = function() {       
                // Create an iFrame with autoplay set to true
                var iframe = document.createElement("iframe");
                iframe.setAttribute("src", "https://www.youtube.com/embed/" + this.id); 

                // The height and width of the iFrame should be the same as parent
                iframe.style.width  = this.style.width;
                iframe.style.height = this.style.height;
                iframe.style.clear = 'both';

                // Replace the YouTube thumbnail with YouTube HTML5 Player
                this.parentNode.replaceChild(iframe, this);

            };
        }
    }

Upvotes: 0

Views: 2732

Answers (1)

Khanh TO
Khanh TO

Reputation: 48972

As you create it onload, just create a html tag:

<iframe src="https://www.youtube.com/embed/yourid"/>

Or use javascript, as there is only 1 should be loaded as default:

window.onload = function(){
   var videos = document.getElementsByClassName("youtube"); 
   if (videos.length > 0){      
            var youtube = videos[0];
             var iframe = document.createElement("iframe");
            iframe.setAttribute("src", "https://www.youtube.com/embed/" + youtube.id); 

            // The height and width of the iFrame should be the same as parent
            iframe.style.width  = youtube.style.width;
            iframe.style.height = youtube.style.height;
            iframe.style.clear = 'both';

            // Replace the YouTube thumbnail with YouTube HTML5 Player
            youtube.parentNode.replaceChild(iframe, youtube);
   }
}

Another case, if you need to keep the onclick and load 1 video by default, just keep your code and write some more lines:

window.onload = function(){
       var videos = document.getElementsByClassName("youtube"); 
       if (videos.length > 0){      
            var youtube = videos[0]; //play the first video onload
            youtube.click(); //trigger click programmatically, this will cause the event handler to be executed and insert an iframe.
       }
}

Upvotes: 1

Related Questions