JSFiddle - React, Tailwind, and code Playground
by ocanal
HTML
<p>
<label for="url">Youtube URL</label><br>
<input type="text" id="url" value="https://www.youtube.com/watch?v=_OBlgSz8sSM" />
</p>
<p id="iconGroup">
<input type="radio" id="r1" name="addIcon" checked value="1">
<label for="r1">Add Play Icon</label>
<input type="radio" id="r2" name="addIcon" value="0">
<label for="r2">No Icon</label>
</p>
<p>
<input type="text" id="iconURL" value="https://i.imgur.com/GrN7tUF.png" />
</p>
<p>
<button id="submit">Get HTML</button>
</p>
<textarea id="htmlResult"></textarea>
<div id="result"></div>
CSS
input[type="text"],
textarea {
max-width: 100%;
min-width: 400px;
}
textarea {
min-height: 100px;
}
JavaScript
function YouTubeGetID(url) {
url = url.split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
return (url[2] !== undefined) ? url[2].split(/[^0-9a-z_\-]/i)[0] : url[0];
}
var url = document.getElementById('url');
var result = document.getElementById('result');
var htmlResult = document.getElementById('htmlResult');
var submit = document.getElementById('submit');
var iconUrl = document.getElementById('iconURL');
var iconGroup = document.getElementById('iconGroup');
var addIcon = document.getElementById('r1');
submit.onclick = function() {
var youtubeId = YouTubeGetID(url.value);
result.innerHTML = '';
if (youtubeId == '') {
alert('please enter a valid youtube URL');
return;
}
var anchor = document.createElement('a');
anchor.setAttribute('href', 'https://www.youtube.com/watch?v=' + youtubeId);
anchor.setAttribute('style', 'display:inline-block;position:relative');
anchor.setAttribute('target', '_blank');
var thumb = document.createElement('img');
thumb.setAttribute('style', 'max-width:100%');
thumb.setAttribute('src', 'https://img.youtube.com/vi/' + youtubeId + '/hqdefault.jpg');
anchor.appendChild(thumb);
if (addIcon.checked) {
var playIcon = document.createElement('img');
playIcon.setAttribute('src', iconUrl.value);
playIcon.setAttribute('style', 'position:absolute;top:0;left:0;right:0;bottom:0;margin:auto;max-width: 80px;');
anchor.appendChild(playIcon);
}
result.appendChild(anchor);
htmlResult.value = result.innerHTML;
htmlResult.select();
document.execCommand('copy');
this.innerHTML = "Copied!";
setTimeout(function() {
submit.innerHTML = 'Get HTML'
}, 1500)
}
iconGroup.onchange = function(e) {
var e = e || window.event;
if (e.target.id === 'r1') {
iconUrl.removeAttribute('disabled');
} else {
iconUrl.setAttribute('disabled', '');
}
submit.click();
}