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 |
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
|
key |
html
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-: http://www.youtube.com/watch?v=6Ai6K2VIEXM" required></textarea>
<input type="submit" value="upload" name="upload">
<div id="feedback"></div>
</form>
<div id="preview"></div>
</div>
CSS
body{
background: #ccc;
}
#wrapper{
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;
}
#feedback{
height: 20px;
width: 435px;
float: right;
text-align: center;
color: black;
font-family: verdana;
}
textarea{
width:490px;
height:40px;
max-width: 490px;
height: 40px;
}
JavaScript
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="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></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 = e.target[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);
if(parts){
var key = parts[4]; //video id
var embedUrl = '<div><iframe width="500" height="300" src="//www.youtube.com/embed/'+key+'?feature=player_detailpage" frameborder="0" allowfullscreen></iframe></div>';
$('#preview').append(embedUrl);
}else{
feedback.innerHTML = 'Wrong Url';
}
}, false);
</script>
No comments:
Post a Comment