jQuery: creare player video dai link di YouTube

jQuery: creare player video dai link di YouTube

jQuery ci permette di modificare la struttura degli elementi con estrema semplicità. Per esempio, dato un link ad un video di YouTube, possiamo creare una nuova struttura che emuli il layout di un lettore video. Vediamo come fare.

Abbiamo dei semplici link come questo:


<a class="youtube-link" href="http://www.youtube.com/watch?v=a_fD19yR3Ww">Video Title</a>

Definiamo subito gli stili CSS per la nuova struttura:


.youtube-box,
.youtube-frame {
  display:block;
  width:420px; /* video width */
  height:315px; /* video height */
  background-color:black;
  background-size:100%;
  position:relative;
  border:none;
  margin:0px auto 15px;
}

.youtube-box span {
  display:block;
  position:absolute;
  top:0px;
  right:0px;
  bottom:0px;
  left:0px;
}

.youtube-box .youtube-title {
  background-color:rgba(0,0,0,0.4);
  font:bold 15px Verdana,Arial,Sans-Serif;
  color:white;
  text-shadow:0px 1px 2px black;
  bottom:auto;
  line-height:30px;
  height:30px;
  overflow:hidden;
  padding:0px 15px;
}

.youtube-box .youtube-bar {
  background: #000;
  height:35px;
  top:auto;
}

.youtube-box .youtube-bar .yt-bar-left {
  background: #999;
}

.youtube-box .youtube-bar .yt-bar-right {
  background: #999;
}

.youtube-box .youtube-play {
  cursor:pointer;
  width:83px;
  height:56px;
  top:50%;
  left:50%;
  margin:-28px 0px 0px -42px;
  background: #999;
  color: #fff;
  line-height: 56px;
  text-align: center;
  text-transform: uppercase;
}

.youtube-box .youtube-play:hover {
  background-color: #000;
}​

Quindi creiamo tale struttura con jQuery utilizzando l'URL del link come base:


$(function() {
    $('a.youtube-link').each(function() {
        var yt_url = this.href,
            yt_id = yt_url.split('?v=')[1],
            yt_title = $(this).text();
        $(this).replaceWith('<div class="youtube-box" style="background-image:url(http://img.youtube.com/vi/' + yt_id + '/0.jpg);"><span class="youtube-title">' + yt_title + '</span><span class="youtube-bar"><span class="yt-bar-left"></span><span class="yt-bar-right"></span></span><span class="youtube-play">Play</span></div>');
        $('div.youtube-box').click(function() {
            $(this).replaceWith('<iframe class="youtube-frame" src="http://www.youtube.com/embed/' + yt_id + '"></iframe>');
        });
    });
});
Torna su