Thursday, February 20, 2014

Embed Youtube Videos With JavaScript

Guyz i got a request from a reader to make a post for dynamic youtube video embed script so its here. Embed youtube videos is very easy the main thing is a key(id) which i will be explaining up next.
Embed Youtube Videos
Embed Youtube Videos

Download Script View Demo 

what is key(id)

in simple words it is the id and every video has is separate id. And this id make every video differnet from each other 


html has nothing interesting in it. Their is a form with a textarea and a submit button and a preview div where videos are displayed
<div id="wrapper">
  <h3>Embed youtube videos</h3>
  <form action="yt.php" method="post" id="yt_form">
   <textarea id="yt-link" name="yt" placeholder="For ex-:" required></textarea>
   <input type="submit" value="upload" name="upload">
   <div id="feedback"></div>
  <div id="preview"></div>


 background: #ccc;
 width: 500px;
 height: 100%;
 border: 1px solid #eee;
 margin-left: auto;
 margin-right: auto;
 top: 0;
 padding: 5px;
 background: #eee;
 box-shadow: 1px 0px 3px #000;
 height: 20px;
 width: 435px;
 float: right;
 text-align: center;
 color: black;
 font-family: verdana;
 max-width: 490px;
 height: 40px;


in JavaScript file we taking the youtube url from the textarea and matching it with the regular experation and breaking the url and getting the key from the url.
<script src="//"></script>
<script type="text/javascript">
//select the form
document.querySelector('#yt_form').addEventListener('submit', function(e){
e.preventDefault();//prevent the form from submiting
var url =[0];//select the textarea
var feedback = document.querySelector('#feedback'); //select the feedback div
var parse_url = /^(https?:\/\/)?(www\.)?youtube\.com\/watch(.*?)v=([^#&$]*)/; //pattern to match the youtube url
var parts = parse_url.exec(url.value);
  var key = parts[4]; //video id
  var embedUrl = '<div><iframe width="500" height="300" src="//'+key+'?feature=player_detailpage" frameborder="0" allowfullscreen></iframe></div>';
  feedback.innerHTML = 'Wrong Url';
}, false);

Like Us on Facebook / Add Hunk As Friend