jQuery: inserire un video di YouTube

Di solito per aggiungere un video preso da YouTube รจ necessario copiare ed incollare il codice HTML preso dal sito nelle nostre pagine. Con jQuery possiamo evitare quest'operazione limitandoci ad usare il solo URL del video. Vediamo come.

Creiamo un semplice plugin che accetta come opzioni l'URL del video, la sua larghezza e altezza e restituisce l'elemento iframe usato da YouTube:


(function($) {
    $.fn.addYouTubeVideo = function(options) {
            
        var that = this;
        var settings = {
        
        	width: 425,
        	height: 344,
        	url: ''
        
        };
        
        options = $.extend(settings, options);
        
        var video = '<iframe width="' + options.width + '" height="' + options.height + 
        			'" src="' + options.url + '" frameborder="0" allowfullscreen></iframe>';
        
        
        return that.each(function() {
        	$(video).appendTo(this);
        });
        
    };
})(jQuery); 

Il plugin aggiunge il video all'elemento corrente. Un esempio:


$(function() {
    
   $('#test').addYouTubeVideo({
   	width: '500', 
   	height: '440', 
   	url: 'http://www.youtube.com/v/Nb_Rch9wmmw?fs=1&amp;hl=en_US'
   }); 
    
    
});

Potete visionare l'esempio finale in questa pagina.

Torna su