Javascript - Displaying a different video depending on clicked video - javascript

So, I'm still new to javascript and everything. What I'm trying to do is when a small video is clicked, display it on the main big video above. This is the script so far, but I'm not sure what I need to add.
<script type="text/javascript">
$(document).ready(function() {
$(".littlevideo").click(function() {
var video = $(this).closest("div").find("video").attr("src")
$('#displayvideo').attr("src",video);
});
});
</script>

you want to do something like:
<script type="text/javascript">
$(document).ready(function() {
$(".littlevideo").click(function() {
var video = $(this).closest("div").find("video").attr("src")
$('#displayvideo').append("<iframesrc="+video+"></iframe>");
});
});
The append basically adds that HTML to the container. you do the +video+ because it adds whatever that value is, to the existing string. This is how you make it dynamic.

We need the rest of the page (preferably), but that piece of code should do what you are wanting. Basically, the code just takes the attributes of the element being clicked on (as long as it has a class of "littlevideo") and transfers it to the #displayvideo element (I'm guessing the "big video" you're talking about). Make sure the little video's elements/tags all have class="littlevideo", and the big video player element/tag has an attribute of id="displayvideo".

Related

How to run code only when iframe loaded

I have been battling with this issue for a few days now and finally found a partial solution but I think it could be improved.
In my project, I have a series of iframes that contain videos. When a link is clicked are displayed with a slide transition and when the link is clicked again the video stops and the span containing the iframe is hidden also with a transition.
This is achieved by adding and removing a css class of "open" that has a height and a transition in it. In addition to this I have an event listener that collapses the containing span also when the video finishes. All this works fine and to save time I am not posting the code.
The issue I was having was with slow page loading times, so I removed the src attribute for the iframes from the html and moved it to my js file and assigned it only after the click is performed. This wasn't working and I realised I needed the iframe to fully load before running the rest of the code inside the "click" method. So I delayed this part of the code by 100ms.
All this works, but I feel it would be better to have the rest of the code run not after a 100ms lapse but when the iframe is loaded (in case page viewed by slower computers). Not sure how to do this.
Here is the code as it stands now:
var player;
var frame = $("#frame");
frame.bind("load", function () {
player = $(this).contents().find("#myVid");
player.on('ended', function () {
frame.removeClass("open");
});
});
$("#clickableLink").click(function(){
if (frame.hasClass("open")) {
frame.removeClass("open");
frame.contents().find('#myVid').get(0).pause();
} else {
function delayed(){
frame.addClass("open");
frame.contents().find('#myVid').get(0).play();
}
frame.attr("src","iframe.html");
setTimeout(delayed, 100);
}
});
Fairly new to development so I am looking for the simplest way to do this. Any help appreciated.
Here is a super simple example of calling code when the iframe has loaded. Check out the onload attribute of the iframe tag:
<head>
<script>
function frameLoaded() {
alert('frame loaded!');
};
</script>
</head>
<body>
<iframe id="frame" src="https://en.wikipedia.org/wiki/HTML_element#Frames" onload="frameLoaded(this)" />
</body>

How to play audio only from youtube videos using HTML and javascript

What I'm trying to do: Create a list of items which contains a link to play audio from a youtube video beside each item
What I'm currently doing: I'm able to do this for a single item using the below:
<div data-video="VIDEO_ID"
data-autoplay="0"
data-loop="1"
id="youtube-audio">
</div>
<script src="https://www.youtube.com/iframe_api"></script>
<script src="https://cdn.rawgit.com/labnol/files/master/yt.js"></script>
This creates a play button and works perfectly on a single item, however will not work with multiple items on the same page presumably since they all use the same ID. Creating a different ID causes the player to not function. Creating two different data-video's with the same ID will only allow the first one to play, the other will appear correctly but not operate when pressing play.
Looking for solution: Preferably how to use the existing script for multiple videos on the same page. Otherwise an alternative solution for playing audio only on youtube videos with a custom play button would be great.
Thanks!
If you want you can just copy paste your code like this
https://jsfiddle.net/8wkjqf3m/
and it works, I'm not sure if you were having a problem doing that or if your problem was elsewhere. It is of course very sloppy looking and the code should be reworked so that you don't have to hard code every function for every video.
I tried to do everything dynamically and failed. I'm not sure if it is possible to dynamically make a function that makes a "new YT.player" for every video id you have and also have the onPlayerReady and onPlayerStateChange functions dynamically made to go with it. I'm sure there is some way but I couldn't figure it out.
The idea though is to make multiple "youtube-audio" divs with different ids for however many youtube players you want to have and have matching multiple "youtube-player" divs for the iframe to function. You can generate that part with javascript if you want so that you don't have to pollute your code with a bunch of repetitive html.
You can make all of your ids dynamically too.
var array = ['put a video id here','put a video id here','put a video id here'];
array = array.map(function(element,index) {
var div = document.createElement('div');
div.setAttribute('id', 'youtube-audio-' + index);
return {'videoId': element, 'div': div };
}
You can just have an array holding the youtube video ids and then initialize all of the divs data-video attributes using
document.getElementById("youtube-audio-1").dataset.video = //youtube video id
I don't see the point in doing all of that dynamically though if there is no way to get around copy pasting x number of "new YT.player"s and "onPlayerReady"s etc...
Good Luck, let me know if I was in the right area or if that was not what you wanted
I have modified the second script so it works as you (or I) want.
To use it use classes instead of IDs. Like the following:
<div data-video="NQKC24th90U" data-autoplay="0" data-loop="1" class="youtube-audio"></div>
<div data-video="KK2smasHg6w" data-autoplay="0" data-loop="1" class="youtube-audio"></div>
Here is the script:
/*
YouTube Audio Embed
--------------------
Author: Amit Agarwal
Web: http://www.labnol.org/?p=26740
edited by Anton Chinaev
*/
function onYouTubeIframeAPIReady()
{
var o= function(e, t)
// This function switches the imgs, you may want to change it
{
var a=e?"IDzX9gL.png":"quyUPXN.png";
//IDzX9gL is the stopped img and quyUPXN the playing img
t.setAttribute("src","https://i.imgur.com/"+a)
// folder or web direction the img is in. it can be "./"+a
};
var counter = 0;
var bigE = document.querySelectorAll(".youtube-audio");
bigE.forEach(function(e)
{
var t=document.createElement("img");
t.setAttribute("id","youtube-icon-"+counter),
t.style.cssText="cursor:pointer;cursor:hand",
e.appendChild(t);
var a=document.createElement("div");
a.setAttribute("id","youtube-player-"+counter),
e.appendChild(a);
t.setAttribute("src","https://i.imgur.com/quyUPXN.png");
e.onclick=function()
{
r.getPlayerState()===YT.PlayerState.PLAYING||r.getPlayerState()===YT.PlayerState.BUFFERING?(r.pauseVideo(),
o(!1, t)):(r.playVideo(),
o(!0, t))
};
var r= new YT.Player("youtube-player-"+counter,
{
height:"0",
width:"0",
videoId:e.dataset.video,
playerVars:
{
autoplay:e.dataset.autoplay,loop:e.dataset.loop
},
events:
{
onReady:function(e)
{
r.setPlaybackQuality("small"),
o(r.getPlayerState()!==YT.PlayerState.CUED, t)
},
onStateChange:function(e)
{
e.data===YT.PlayerState.ENDED&&o(!1, t)
}
}
})
counter++;
});
}

JS / JQUERY iframe.contents() syntax

I'm currently working on a project which includes when the user hovers over a certain div then it will play the associated audio file and stop all other audio elements on the page that contain the class 'stoppable' in them.
I've got the code working but now I'm having that page as an iFrame on another page which can insert elements into the iframe, so I have to keep adding iframe.contents on elements to make them work.
On the code below it detects when the user has entered the div and plays the correct audio however it does not stop all the other audio elements.
I believe I have the incorrect syntax on the
$('.stoppable:not($("#new-audio-476333", iframe.contents()))
section, and I'm not sure what the correct syntax would be.
var iframe = $('#clientframe');
$('#476333',iframe.contents()).mouseenter(function() {
$('.stoppable:not($("#new-audio-476333", iframe.contents()))').each(function(){
this.pause(); this.currentTime = 0;
});
var audio = $('#new-audio-476333', iframe.contents())[0];audio.pause();audio.play(); });
Any help would be greatly appreciated.
Thanks!
-Hopeless
$('.stoppable:not(#new-audio-476333)', iframe.contents())
This means that elements with class name stoppable which its id is not new-audio-476333.

click a button to load a different video player into div

i'm working on adding a video to the home page of a site i'm working on. ideally, i'd like to show the youtube version by default, and add a button underneath that says something like "don't have access to youtube? click here to watch an alternate version".
once clicked, a different player will load into the same video div and replace the youtube version.
we have the video uploaded to youtube, and also have an html5 version on the site that is played via the video.js plugin for wordpress.
how can i load the alternate html5 video player into the div via a button click (without refreshing the page if possible)? i'm assuming this can be done via javascript / jquery / ajax somehow, but I'm not sure how to do this (my js level is novice).
thanks!!
You can clear the div out with:
$("#yourDivID").empty()
Then populate the div with new content
var newHtml = "Whatever you want!"
$("#yourDivID").append(newHtml);
Or
$("#yourDivID").html(newHtml);
Here's a very primitive example of replacing content in a Div: http://jsfiddle.net/FJuwd/
Html
<div id="myvideodiv"> </div>
In script
mybutton.click(function(){
playerMethod("myvideodiv").setup({ //here player intializations based on sepecific type
file: "/uploads/example.mp4",
height: 360,
image: "/uploads/example.jpg",
width: 640
});
})
see example here.
jQuery solution: Just create div and populate with video on button click. Many ways to do this. The check for length is only there to eliminate putting another video up.
<div id="player"><div>
<button id="clickme">Click to play video</button>
$("#clickme").on("click", function(e) {
if($('#myfileplayer').length == 0) {
var mydiv = $("#player");
var myvideo = $("<video id='myfileplayer' src='http://clips.vorwaerts-gmbh.de/big_buck_bunny.ogv' width='320' height='240' controls></video>");
mydiv.append(myvideo);
}
});
See example
thanks so much everyone for all of the help. love this place.
i was actually able to work this out more easily by just toggling divs that contain the two different videos. not sure why i didn't think of this initially. doesn't actually remove the content, just hides it, but i think it will work for me.
html
<div id="youtube">my youtube vid</div>
<div id="html5" style="display:none;">my alternate vid</div>
<input type="button" value="switch video" id="click"/>
jquery
$(function(){
$('#click').click(function(){
$('#youtube').toggle();
$('#html5').toggle();
});
});
i also tried this with the js, so the youtube video would be removed & stop playing when the divs are toggled
$(function(){
$('#click').click(function(){
$('#youtube').toggle();
$('#html5').toggle();
$('#youtube').empty();
});
});
this works, but i wasn't sure how to add the youtube video back when toggling back. not really a big deal - just something i was curious about. i'm assuming it can be done with .append.
problem with this is that both of the vids exist in the wordpress page as shortcodes, so it complicates things a bit. i just wrapped the shortdoces in divs with these ids in the wordpress page to get the toggle working, and added the js to my page template. thx again!

Need to set 1 span's style to display:block on page load for an image gallery made up of span's set to display:none

i have some javascript in the head of a page that controls an image gallery where the user clicks a thumbnail image and a larger image and some text are revealed in a span. there are 10 of these thumbnails per page and i need to find out how to set the 1st thumbnail's hidden span to "block" on page load.
<script type="text/javascript">
function hideSpan(spanName) {
var obj = document.getElementById(spanName);
obj.style.border="0px";
obj.style.color="#fff";
obj.style.display="none";
obj.style.left="333px";
obj.style.padding="0";
obj.style.position="absolute";
obj.style.top="55px";
obj.style.width="244px";
}
function showSpan(spanName) {
var spanEl, count = 1;
while(spanEl = document.getElementById('link' + count++)){
spanEl.style.display = 'none';
}
var obj = document.getElementById(spanName);
obj.style.display="block";
}
</script>
any help with this is VERY appreciated thank you.
The simple, breezy way is to do this:
<body onload="showSpan('link1');">
The trouble here is that the onload event attached to body that way is executed a little late in the page loading (After all the parts-- including images-- are loaded) so it'll be murder for your dial up users. jQuery implements a much better way:
$(document).ready(function () {
showSpan('link1');
});
If you're not using jQuery, then someone here much wiser than I more than likely knows the correct way to do it using "proper" JavaScript, I don't remember the event name that jQuery uses off the top of my head.

Categories

Resources