Yusaf Khaliq
Yusaf Khaliq

Reputation: 3393

Replacing youtube image placeholders to video

I have a jquery function which replaces a Link within two values with an image for e.g

<div class="comment">
[youtube]http://www.youtube.com/watch?v=T1hf4B5pyjQ&feature=grec_index[/youtube]
random text
</div>

will be output as

<div class="comment"><img width="420" height="315" src="http://i4.ytimg.com/vi/T1hf4B5pyjQ/hqdefault.jpg"></img>
random text
</div>

with this function below

var youtubeTag = /\[youtube]https?:\/\/(?:www\.)?youtu(?:be\.com|\.be)\/(?:watch\?v=|v\/)?([A-Za-z0-9_-]+)([a-zA-Z&=;_+0-9*#-]*?)\[\/youtube]/,
    youtubeHTML = '<img width="420" height="315" src="http://i4.ytimg.com/vi/$1/hqdefault.jpg"></img>';
$(".comment").each(function(){
    var $this = $(this);
    $this.html($this.html().replace(youtubeTag, youtubeHTML))
});

what I'm trying to do is onclicking the image replace youtubeHTML with youtubeIFRAME i have tried this below or check it out on JSFIDDLE http://jsfiddle.net/yusaf/uLTzw/28/

var youtubeTag = /\[youtube]https?:\/\/(?:www\.)?youtu(?:be\.com|\.be)\/(?:watch\?v=|v\/)?([A-Za-z0-9_-]+)([a-zA-Z&=;_+0-9*#-]*?)\[\/youtube]/,
    youtubeHTML = '<img width="420" height="315" src="http://i4.ytimg.com/vi/$1/hqdefault.jpg"></img>';
    youtubeIFRAME = '<iframe width="420" height="315" src="http://www.youtube.com/embed/$1?rel=0" frameborder="0" allowfullscreen></iframe>';
$(".comment").each(function(){
    var $this = $(this);
    $this.html($this.html().replace(youtubeTag, youtubeHTML))
});

$("img").click(function(){
    var $this = $(this);
    $this.html($this.html().replace(youtubeHTML, youtubeIFRAME))
});

Upvotes: 2

Views: 2192

Answers (1)

kubetz
kubetz

Reputation: 8556

The problem is that $1 part inside youtubeHTML which is not allowing the handler to replace the HTML correctly.

One quick solution is to use data attribute on youtubeHTML and store the link also there. Then simply replace the $1 inside the youtubeIFRAME with the value of that data attribute.

Here is the snippet.

var youtubeTag = /\[youtube]https?:\/\/(?:www\.)?youtu(?:be\.com|\.be)\/(?:watch\?v=|v\/)?([A-Za-z0-9_-]+)([a-zA-Z&=;_+0-9*#-]*?)\[\/youtube]/;
var youtubeHTML = '<img width="420" data-address="$1" height="315" class="youtube" src="http://i4.ytimg.com/vi/$1/hqdefault.jpg"></img>';
var youtubeIFRAME = '<iframe width="420" height="315" class="youtube" src="http://www.youtube.com/embed/$1?rel=0" frameborder="0" allowfullscreen></iframe>';

$(".comment").each(function(){
    var $this = $(this);
    $this.html($this.html().replace(youtubeTag, youtubeHTML));
});

$("img.youtube").click(function(){
    var $this = $(this);   
    $this.replaceWith(youtubeIFRAME.replace("$1", $this.attr("data-address")));
});

EDIT: In case anyone is interested in a way how to write some kind of short "click here" text over the placeholder images have a look here.

Upvotes: 3

Related Questions