Add video to page on Button click - javascript

I am a beginner JS user, and I am trying to get a video to play on fullscreen and replace an invisible div further down on the page. I started with a guide from Chris Ferdinandi.
In his guide, the video replaces the image that is clicked. I would like to have the div later down on the page to be replaced on the click.
Any guidance would be great!
HTML
<a data-video="480459339" class="stylsheetref" href="#" target="">Watch the Tour</a>
<div id="video-replace"></div>
Javascript (modified from this guide)
<script>
if (!Element.prototype.requestFullscreen) {
Element.prototype.requestFullscreen = Element.prototype.mozRequestFullscreen || Element.prototype.webkitRequestFullscreen || Element.prototype.msRequestFullscreen;
}
// Listen for clicks
document.addEventListener('click', function (event) {
//Set invisible Div (new code added by me)
var videonew = '#video-replace');
// Check if clicked element is a video link
var videoId = event.target.getAttribute('data-video');
if (!videoId) return;
// Create iframe
var iframe = document.createElement('div');
iframe.innerHTML = '<p>x</p><iframe width="560" height="960" src="https://player.vimeo.com/video/' + videoId + '?rel=0&autoplay=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>';
var video = iframe.childNodes[1];
// Replace the image with the video
event.target.parentNode.replaceChild(video, videonew);
// Enter fullscreen mode
video.requestFullscreen();
}, false);
</script>

There are problems in your code.
var videonew = '#video-replace'); there's an orphan ), since you are using this in the `replaceChild``method I assume you want the variable to reference to an element.
So change it to
var videonew = document.querySelector('#video-replace');
Pro tip: Using the Developer console during development can help you figure out such errors in your code.

Related

Adding a close function that doesn't reposition page

I added the ability to display a youtube video within a Lightbox on my website. However, the code I found to help with this doesn't have a close (X) on the Lightbox. Whilst it does close by just clicking anywhere on the mask, I think not all web users are going to realise this, so I added a simple
x
onto the Lightbox div. Whilst this does actually give a functional closing (X) on the lightbox, it has the undesirable effect of the page being back at the top when the Lightbox has closed.
What I ideally want is for the Lightbox to simply close, and the page remains in the same place as it was when it opens, which is what happens if I just click on the mask.
I can see there is a section commented '// Hide lightbox when clicked on', but I have no clue how I can make an (X) also trigger this same action.
Here is the complete script used.
<div id="youtubelightbox" class="parent">x
<div class="centeredchild">
<div class="videowrapper">
<div id="playerdiv"></div>
</div>
</div>
</div>
<script>
// load Youtube API code asynchronously
var tag = document.createElement('script')
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0]
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag)
var isiOS = navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)/i) != null //boolean check for iOS devices
var youtubelightbox = document.getElementById('youtubelightbox')
var player // variable to hold new YT.Player() instance
// Hide lightbox when clicked on
youtubelightbox.addEventListener('click', function(){
this.style.display = 'none'
player.stopVideo()
}, false)
// Exclude youtube iframe from above action
youtubelightbox.querySelector('.centeredchild').addEventListener('click', function(e){
e.stopPropagation()
}, false)
// define onYouTubeIframeAPIReady() function and initialize lightbox when API is ready
function onYouTubeIframeAPIReady() {
createlightbox()
}
// Extracts the Youtube video ID from a well formed Youtube URL
function getyoutubeid(link){
// Assumed Youtube URL formats
// https://www.youtube.com/watch?v=Pe0jFDPHkzo
// https://youtu.be/Pe0jFDPHkzo
// https://www.youtube.com/v/Pe0jFDPHkzo
// and more
//See http://stackoverflow.com/a/6904504/4360074
var youtubeidreg = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i;
return youtubeidreg.exec(link)[1] // return Youtube video ID portion of link
}
// Creates a new YT.Player() instance
function createyoutubeplayer(videourl){
player = new YT.Player('playerdiv', {
videoId: videourl,
playerVars: {autoplay:1,
rel:0,
showinfo:0,
fs:0
}
})
}
// Main Youtube lightbox function
function createlightbox(){
var targetlinks = document.querySelectorAll('.lightbox')
for (var i=0; i<targetlinks.length; i++){
var link = targetlinks[i]
link._videoid = getyoutubeid(link) // store youtube video ID portion of link inside _videoid property
targetlinks[i].addEventListener('click', function(e){
youtubelightbox.style.display = 'block'
if (typeof player == 'undefined'){ // if video player hasn't been created yet
createyoutubeplayer(this._videoid)
}
else{
if (isiOS){ // iOS devices can only use the "cue" related methods
player.cueVideoById(this._videoid)
}
else{
player.loadVideoById(this._videoid)
}
}
e.preventDefault()
}, false)
}
}
if (isiOS){ // iOS devices can only use the "cue" related methods
player.cueVideoById(this._videoid)
}
else{
player.loadVideoById(this._videoid)
}
After some trial and error I figured this out.
I changed the html to
<div id="youtubelightbox" class="parent">
<div class="centeredchild"><div id="x">x</div>
<div class="videowrapper">
<div id="playerdiv"></div>
</div>
</div>
</div>
And added the following to the script
x.addEventListener('click', function(){
youtubelightbox.style.display = 'none'
player.stopVideo()
}, false)

Embedded Video keeps playing even after closed

I have a video which would keep playing even after I close it.
I feel there is something I am missing in my jQuery.
Could anyone please help me.
Below is the code related to it.
Jquery
$("[data-media]").on("click", function(e) {
e.preventDefault();
var $this = $(this);
var videoUrl = $this.attr("data-media");
var popup = $this.attr("href");
var $popupIframe = $(popup).find("iframe");
$popupIframe.attr("src", videoUrl);
var left = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var left = left/2 - 340;
var top = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var top = top/2 - 180
document.getElementById("vid").style.top = top + "px";
document.getElementById("vid").style.left = left + "px";
$this.closest(".page").addClass("show-popup");
});
$(".popup").on("click", function(e) {
e.preventDefault();
e.stopPropagation();
$(".page").removeClass("show-popup");
});
$(".popup > iframe").on("click", function(e) {
e.stopPropagation();
});
HTML
<div class="page"> <!-- class "page" is required for video to work-->
<div class="popup" id="media-popup"> <!-- video embedded -->
<iframe id="vid" src="http://testvideo.com" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div><!-- popup -->
</div>
You have a list of video url when you click one, a popup comes up showing the corresponding video.When you are done with that video you want to remove it by clicking outside the iframe but inside popup.
Here is the problem
You are using this $(".page").removeClass("show-popup");
to get the second part done removing this class will simply hide it using css display orvisibility it's like making something invisible but still you can hear it, so video is invisible but it's still there playing .To fix this you need to wipe the src of iframe
$('.page iframe').attr("src", '');

javascript turn a YouTube link into embed video

I Have Many Links On My Page All Jotted Around In Random Places. If Have The Links Like This:
https://youtu.be/4tG274QuqHM
or
https://youtube.com/watch?v=4tG274QuqHM
or
Any Other YouTube Video Link Format
Is There Any Way In JavaScript To Get Any Form Of YouTube Link And Turn It Into A YouTube Embed Iframe, By Using JavaScript To Make It End Up Looking Like This;
<iframe width="420" height="345" src="http://www.youtube.com/embed/4tG274QuqHM?autoplay=0&autohide=1&controls=2&rel=0" frameborder="0" allowfullscreen="true"></iframe>
Could Anyone Fix This Code To Make It Work???
$(document).ready(function() {
$('a').each(function() {
var matches = $(this).attr("href").match(/^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/);
if(matches){
$(this).attr("class","youtube-link");
}
});
$('a.youtube-link').each(function() {
var yt_url = this.href,
yt_id = yt_url.split('?v=')[1],
yt_id = yt_url.split('embed/')[1],
yt_title = $(this).text();
$(this).replaceWith('<iframe style="max-width:560px;max-height:315px;" width="600" height="600" src="http://www.youtube.com/embed/' + yt_id + '?rel=0" frameborder="0" allowfullscreen></iframe>');
});
});
I would check this link out. It's Google's documentation on a Youtube iFrame.
https://developers.google.com/youtube/player_parameters#Embedding_a_Player
You can simply extract the href value on click on the anchor tag and replace the existing anchor tag with a iframe tag.
https://youtube.com/watch?v=4tG274QuqHM
<br>
http://www.youtube.com/embed/XGSy3_Czz8k
<script>
$('a').click(function(e)
{
var target = $(this).attr('href');
var iframe = $('<iframe/>',{ width: "420", height: "315" , src : target});
$(this).replaceWith(iframe);
e.preventDefault();
});
</script>
Example : https://jsfiddle.net/4nqhqu03/

JQuery Replaces Iframe Multiple Times

If you take a look at this page here, you'll see that I've created a bit of a Youtube video gallery. When it works, it should replace the video in the main section of the page (at the top) with the thumbnail that is clicked and the text on the right is also replaced with text related to that video.
The text replacement seems to be working perfectly but I'm experiencing an issue where during the swap, the iFrame seems to be getting placed multiple times and so the video plays 2-3 times.
The Javascript is below -- is this something I've missed?
<script>
function replaceVideo(id) {
originalSrc = jQuery("iframe", "#" + id).attr("src");
autoPlay = originalSrc + "&autoplay=1";
jQuery("iframe", "#" + id).attr("src", autoPlay);
video = jQuery(".video-wrap", "#" + id).html();
jQuery(".flex-video").html(video);
text = jQuery(".video-description", "#" + id).html();
jQuery(".vid_desc").html(text);
jQuery("iframe", "#" + id).attr("src", originalSrc);
}
jQuery(".video-list li").click(function() {
id = jQuery(this).attr("id");
replaceVideo(id);
});
jQuery(window).load(function() {
if(window.location.search.substring(1)) {
element = window.location.search.substring(1).split('&');
if (document.getElementById(element[0])) {
document.onload = replaceVideo(element[0]);
}
}
});
</script>
Thanks!
Run jQuery(".flex-video") this in your javascript console. You'll see there are THREE divs that have that class. So jQuery(".flex-video").html(video); this line of JS changes the inner HTML of 3 elements to be the iframe.
<div class="flex-video widescreen">
<iframe width="583" height="328" src="http://www.youtube.com/embed/TWmFCX40BQc?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
</div>
You need to make the above div distinguishable from the other flex-video frames. Give the parent div an id or another class or something to query off of. Do that, and then you'd be fine.
EDIT: By the way, this code is wrong:
if(window.location.search.substring(1))
{
element = window.location.search.substring(1).split('&');
if (document.getElementById(element[0])) {
document.onload = replaceVideo(element[0]);
}
}
setting document.onload to a function call will call replaceVideo and set the onload property to whatever it returns, which is nothing. It may appear to work because the video plays, but that's just because you're calling the replaceVideo method. Setting your if to this, will probably be sufficient for you (unless you can explain why you're setting it to onload)
if(document.getElementById(element[0]))
replaceVideo(element[0]);

Rendering Youtube Video in a WYSIWYG

I am creating a custom WYSIWYG from scratch using JavaScript. All of it is working fine (like inserting pictures), but when I click on submit and the content gets added to my database, the YouTube video gets inserted like this:
<div><br></div><div><br><div><br></div></div>
I have created a JavaScript file that the WYSIWYG parses to:
function iImage(){
var imgSrc = prompt('Enter image location', '');
if (imgSrc != null){
richTextField.document.execCommand('insertimage', false, imgSrc);
}
}
function iVideo(){
var urlPrompt = prompt("Enter Youtube Url:", "http://");
var urlReplace = urlPrompt.replace("watch?v=", "embed/");
var embed = '<iframe src="'+urlReplace+'" allowfullscreen="true" width="480" frameborder="0" height="390">';
if($.browser.msie){
richTextField.document.createRange().pasteHTML(embed);
}else{
richTextField.document.execCommand("Inserthtml", false, embed);
}
}
function submit_form(){
var theForm = document.getElementById("blogForm");
theForm.elements["blogbody"].value = window.frames['richTextField'].document.body.innerHTML;
theForm.submit();
}
You can see that my iImage function works, but not my iVideo.
Can anyone help?
Just to let you know i have edited my script to this...
function iVideo(){
var urlPrompt = prompt("Enter Youtube Url:", "http://");
var urlReplace = urlPrompt.replace("http://www.youtube.com/watch?v=", "http://www.youtube.com/embed/");
var embed = '<iframe src="'+urlReplace+'" allowfullscreen="true" width="480" frameborder="0" height="390"></iframe>';
if($.browser.msie){
richTextField.document.createRange().pasteHTML(embed);
}else{
richTextField.document.execCommand("Inserthtml", false, embed);
}
}
but still no joy
I have got it. This is the code below
function iVideo(){
var urlPrompt = prompt("Enter Youtube Url:", "http://");
var urlReplace = urlPrompt.replace("watch?v=", "embed/");
var embed = '<iframe title="YouTube video player" src="'+urlReplace+'" allowfullscreen="true" width="480" frameborder="0" height="390">';
if(embed != null){
richTextField.document.execCommand("Inserthtml", false, embed);`
}
}
It working on my sites right now.
Ultimate
The reason you don't see a Youtube.com is because it will be added by you upon uploading. In the form where you write content you intend to upload to your site, You are to click on a Add Video link which will tricker off the first line in the code to popup a window requesting you to submit your Youtube video link, which looks something like http://youtube.com/theVideoLink. The link you add will then be placed where you have src="'+urlReplace+'" that is.
Well, I am a begginner at javascript, but I don't see anywhere were it adds youtube.com to it, all I see is the watch?v=.
As I said, a beginners opinion.
Are you able to first try a hardcoded/static version like below first?
- might be just syntax or one of your variables not set.
<script type="text/javascript">
function iVideo(){
var youtubeiframe='<iframe type="text/html" width="640" height="385" src="http://www.youtube.com/embed/AsbagZvkrbo" frameborder="0"></iframe>';
richTextField.document.execCommand ("insertHTML", false, youtubeiframe);
}
</script>

Categories