Change html with javascript
I am developing a small extension for myself. The goal is simple: you click on an extension, you enter a YouTube link, and the video plays inside your extension.
Here is my HTML
<body>
Youtube Link: <input type="text" id="link" name="firstname">
<button type="button" id="do-link"> Go ! </button>
<script src="popup.js"></script>
<p id="write">Here your link</p>
<iframe id="ytplayer" title="YouTube video player" class="youtube-player" type="text/html"
width="640" height="390" src="https://www.youtube.com/watch?v=DTqTs15Hc9w"
frameborder="0" allowFullScreen></iframe>
</body>
And my JS:
var a;
function link() {
a = document.getElementById('link').value;
document.getElementById('ytplayer').src = a;
console.log(a);
}
document.getElementById('do-link').onclick = link;
So this basically just prints to the console what's inside my textbox. And it displays the KSI video (or whatever video you want if you put the hte link. I want to know if there is an easy way to replace the YouTube links with a link written by the user in the textbox?
source to share
You can change the SRC IFRAME, but you need to use the embed url from Youtube, not just the IFRAME page on Youtube, otherwise you will get a cross domain error.
Also, from the Youtube url, you need to get the video id and use it in the embedded SRC
Editing the code:
Html
`Youtube Link: <input type="text" id="link" name="firstname">
<button type="button" id="do-link"> Go ! </button>
<script src="popup.js"></script>
<p id="write">Here your link</p>
<iframe id="iframe_id" width="640" height="390" src="//www.youtube.com/embed/u1vhQOOZUF4" frameborder="0" allowfullscreen></iframe>`
Js
var a;
function link() {
a = document.getElementById('link').value;
var videoid = youtube_parser(a);
var new_link = "https://www.youtube.com/embed/" + videoid;
document.getElementById('write').innerHTML = new_link;
document.getElementById('iframe_id').src = new_link;
console.log(new_link);
}
document.getElementById('do-link').onclick = link;
function youtube_parser(url){
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = url.match(regExp);
if (match&&match[7].length==11){
return match[7];
}else{
alert("Url incorrecta");
}
}
Here is a working version (fiddle): http://jsfiddle.net/x7mxos14/
source to share