Categories
Code Snippet

Snippet – Create YouTube Embedded Frame [JS]

Just share a small Javascript function to help you make a iframe embedded for your content.

There exists a regular express to verify the link content

Here’s right away:

function youtubeEmbeddedFrame (content){
	var matches = /(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g.exec(content);
	if(!matches){
		return null;
	}
	
	var iframe = jQuery('<iframe width="300" height="200" frameborder="0" allowfullscreen />');
	iframe.attr('src', location.protocol + '//www.youtube.com/embed/' + matches[1]);
	
	return iframe;
}

You can call in your Javascript code as:

youtubeEmbeddedFrame("https://www.youtube.com/watch?v=J2ADdDCvaj4")

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.