Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  41] [ 4]  / answers: 1 / hits: 5942  / 11 Years ago, sat, january 4, 2014, 12:00:00

I've tried replace youtube and vimeo url with embed code in javascript code.



I've used this code:



EXAMPLE 1:



HTML:



<div id=divContent></div>


JAVASCRIPT:



$(#divContent).html('http://www.youtube.com/watch?v=t-ZRX8984sc <br /> http://vimeo.com/82495711 <br /> http://youtu.be/t-ZRX8984sc');

$('#divContent').html(function(i, html) {
return html.replace(/(?:http://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch?v=)?(.+)/g, '<iframe width=200 height=100 src=http://www.youtube.com/embed/$1 frameborder=0 allowfullscreen></iframe>').replace(/(?:http://)?(?:www.)?(?:vimeo.com)/(.+)/g, '<iframe src=//player.vimeo.com/video/$1 width=200 height=100 frameborder=0 webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>');

});


DEMO EXAMPLE 1: http://jsfiddle.net/88Ms2/301/ - It's not working.



EXAMPLE 2



HTML:



<div id=divContent>
http://www.youtube.com/watch?v=t-ZRX8984sc
<br />
http://vimeo.com/82495711
<br />
http://youtu.be/t-ZRX8984sc
</div>


JAVASCRIPT:



$('#divContent').html(function(i, html) {
return html.replace(/(?:http://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch?v=)?(.+)/g, '<iframe width=200 height=100 src=http://www.youtube.com/embed/$1 frameborder=0 allowfullscreen></iframe>').replace(/(?:http://)?(?:www.)?(?:vimeo.com)/(.+)/g, '<iframe src=//player.vimeo.com/video/$1 width=200 height=100 frameborder=0 webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>');

});


DEMO EXAMPLE 2: http://jsfiddle.net/88Ms2/300/ - It's working



I've retrieved a data from database using ajax. I need the data with html code insert into div using javascript. How can I modify the example 1 to the correct code?


More From » jquery

 Answers
1

In example 1, change the javascript code to:



$('#divContent').contents()
.filter(function(){
return this.nodeType === 3;
})
.map(function(index, text){
$(text).replaceWith(
text.textContent.replace(/(?:http://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch?v=)?(.+)/g, '<iframe width=200 height=100 src=http://www.youtube.com/embed/$1 frameborder=0 allowfullscreen></iframe>').replace(/(?:http://)?(?:www.)?(?:vimeo.com)/(.+)/g, '<iframe src=//player.vimeo.com/video/$1 width=200 height=100 frameborder=0 webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>')
);
})


It should work now.


[#49014] Thursday, January 2, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
phoebea

Total Points: 607
Total Questions: 100
Total Answers: 78

Location: Netherlands
Member since Thu, Jul 1, 2021
3 Years ago
;