Here is my HTML section..
<section id ="information">
<video id ="videoName" width="800" height="400" controls
onplay="myAnimationPicture()"">
<source src="video/videoName.mp4" ; type="video/mp4">
Your browser does not support the video tag.
</video>
</section>
Here is my Javascript section...
document.getElementById('videoName').addEventListener('ended',deleteVideo,false);
function deleteVideo(e)
{
var elem = document.getElementById('videoName');// What you
want to do after the event
elem.remove();
}
Please let me know if it is even possible. What I eventually want to try and accomplish is after the user watches the video, the video is removed and is replaced with a horizontal menu for stats information.
Thank you,
Josh
You could do something like this:
document.getElementById('videoName').addEventListener('ended',myHandler,false);
function myHandler(e) {
//remove video here
//add menu here
}
Which attaches a callback function (myHandler) that gets triggered after the video is done.
Get the parent event target and remove the child ('#videoName')
function deleteVideo(e) {
e.target.parentNode.removeChild(e.target)
}
So on my website, there are few simple audio players that are live streaming radio stations.
Here's how it looks...
audio player pic
And here is my code for these audio players:
<audio src="https://cbc_r2_tor.akacast.akamaistream.net/7/364/451661/v1/rc.akacast.akamaistream.net/cbc_r2_tor" controls style="width:75px;" volume="1.0"> </audio>
<audio src="http://204.2.199.166/7/288/80873/v1/rogers.akacast.akamaistream.net/tor925" controls="true" style="width:75px;" volume="1.0"></audio>
<audio src="http://indie.streamon.fm:8000/indie-48k.aac" controls="true" style="width:75px;" volume="1.0"></audio>
These players don't pause automatically when the other is being played.
I did some research on this topic and found this script here on stack...
<script>
document.addEventListener('play', function(e){
var audios = document.getElementsByTagName('audio');
for(var i = 0, len = audios.length; i < len;i++){
if(audios[i] != e.target){
audios[i].pause();
}
}
}, true);
</script>
Btw I'm using wix.com to build all of this and I'm really not sure where to put this script exactly. I tried to put it beneath in Edit code where the code of the individual audio player is but that doesn't seem to work at all.
What would be the simplest way to achieve this?
I'm a beginner so any help would be appreciated. Thanks in advance :)
Wix does not expose the window or document objects.
However, you can use $w().
As in let myElement = $w("#myElement");
See the site for more: https://www.wix.com/code/reference/%24w.html
EDIT
I'd advise against using 'document' as a variable name here, it could be confused with being the real document object.
Here are some pointers from the Wix site I indicated above that should sort out what you are trying to do...
Getting elements from the page (from Wix):
let imageElements = $w("Image");
let firstImage = imageElements[0];
Just replace 'Image' with 'Audio';
Use the onReady event (from Wix):
function onReady(initFunction: ReadyHandler): void
callback ReadyHandler(): Promise<void>
Put your initialisation code in the onReady event - otherwise the DOM may not be ready.
Creating your event handler (from Wix):
$w("#myElement").onEvent( (event, $w) => {
let targetId = event.target.id; // "myElement"
});
$w("#myElement").onEvent( (event, $w) => {
let eventType = event.type; // "click"
});
So, use something like:
$w.onReady(function() {
let myAudios = $w("audio");
myAudios.onEvent((event, $w) => {
let eventType = event.type;
if(eventType == "play") // or use 'click' if play is not exposed
{
let targetId = event.target.id;
for(var i = 0; i < myAudios.length; i++) {
if(myAudios[i].id != targetId) {
myAudios[i].pause();
}
}
}
});
});
Final note.
You'll want to put your javascript code on the page you are working with using the code panel.
From Wix:
The Public section of the sidebar contains files that are publicly
accessible from your site. You can create JavaScript files and text
files for use in public, and you can organize these files in folders.
Your page and site code, which are also publicly accessible, do not
appear in the Public section.
To edit page and site code, use the code panel.
See this short video from Wix (you can jump to 30secs) to see where the code panel is. https://support.wix.com/en/article/working-in-the-code-panel
EDIT 2
I finally gave in, and created a Wix account to test this.
Unfortunately, you are limited to what you can do in javascript regarding the APIs they expose from the objects placed on the page.
However, there is a way to get your functionality:
Create an HTML iframe.
Click Add, then More, then drag the HTML iframe onto your page.
Double-click it, or select it and click 'Edit Code', then add all of the below to the 'Add your code here (HTTPS only)' box.
<audio src="http://narwakk.free.fr/musiques/Bob/Bob Marley - Roots, Rock, Reggae.mp3" controls> </audio>
<audio src="https://jazz-wr06.ice.infomaniak.ch/jazz-wr06-64.aac" controls></audio>
<audio src="https://hpr.dogphilosophy.net/test/wav.wav" controls></audio>
<script>
document.addEventListener('play', function (e) {
var audios = document.getElementsByTagName('audio');
for (var i = 0, len = audios.length; i < len; i++) {
if (audios[i] != e.target) {
audios[i].pause();
}
}
}, true);
</script>
Remove any code you had for the audios before, preview it, and you should be done (apart from using your own sounds).
I'll leave the previous edit as is, because it generally works - just not for audio tags...
UPDATE: I was using the Fotorama plugin and it seems that the bottom menu was causing the problem. Disabling that menu by putting div-tags around the video-tags made the function for setting resolution work. Thanks for the help and encouragement. For the bottom menu I create a simple one using link buttons that link to a similar page with the next video.
I have written JavaScript code that changes the resolution of a video based on input of a option/select-element. It works. The problem is that it stops working when I put exactly the same code inside a function (so that the code can be executed multiple times - each time option/select-element is changed.)
Here is an image of the videoplayer and the option/select-element I have added
Here is the code for the option/select-element:
<li class="porfolionav">
<select id="selectQuality" onchange="changeVidQualityFunction()">
<option value="1080" selected="selected" disabled="disabled">Videokvalitet</option>
<option value="1080" id="1080">HD 1080</option>
<option value="480" id="480">SD 480</option>
<option value="320" id="320">SD 320</option>
</select>
</li>
Here is the code for the videos:
<div class="fotorama" data-width="1209px" data-height="680px" data-allowfullscreen="false" data-arrows="true" data-click="true" data-swipe="true" data-autoplay="false" data-transition="slide" data-clicktransition="slide" data-shuffle="false">
<video id="video1V" height="680px" controls data-caption="320 OGG" poster="videos/img/thumb1.jpg">
<source src="videos/test_q_320" id="video1">Your browser does not support HTML5 video.
</video>
<video id="video2V" height="680px" controls data-caption="480 OGG" poster="videos/img/thumb2.jpg">
<source id="video2" src="videos/test_q_480.ogg" id="video2">Your browser does not support HTML5 video.
</video>
<video id="video3V" height="680px" controls data-caption="1080 OGG" poster="videos/img/thumb3.jpg">
<source id="video3" src="videos/test_q_1080.ogg" id="video3">Your browser does not support HTML5 video.
</video>
</div>
And here is the code for the changing resolution (works when not in a function):
<script>
function changeVidQualityFunction(){
$chosenVidQuality = document.getElementById("selectQuality").value;
$trulycompletevideolink = document.getElementById("video1").src;
$step1 = document.getElementById("video1").src.split("_q_");
//COMMENT: step1[0] is the url from start and including the first part of the filename (not the "_q_"-part and the format)
$upToVidName = $step1[0];
//COMMENT: step1[1] is the resolution and format, e.g. 320.ogg
$step2 = $step1[1].split(".");
//COMMENT: step2[0] is the resoltion e.g. 720 ,step2[1] is the format (without the dot in front of the format type) e.g. ogg
$vidresolution = $step2[0];
$vidformat = $step2[1];
$vidresolution = $chosenVidQuality;
$result = $upToVidName+"_q_"+$vidresolution+"."+$vidformat;
$('#video1').attr('src', $result);
$('#video1V').attr('data-caption', $vidresolution+" OGG");
$('#video1V').load();
window.alert("video1 attr src:"+document.getElementById("video1").src); //shows updated URL
}
</script>
Thanks
On your head tag place this <script src="jquery-1.12.2.js" charset="utf-8"></script> to include jquery library since your are using functions from jquery.
and from this line
<select id="selectQuality" onchange="changeVidQualityFunction()">
change it to
<select id="selectQuality" name="video_selected">
and edit your script that follows the rule of jquery, make proper declarations as follows.
function changeVidQualityFunction() {
var ev = $('#selectQuality').val();
console.log(ev);
var chosenVidQuality = $('#selectQuality').val();
var trulycompletevideolink = document.getElementById("video1").src;
var step1 = document.getElementById("video1").src.split("_q_");
//COMMENT: step1[0] is the url from start and including the first part of the filename (not the "_q_"-part and the format)
var upToVidName = step1[0];
//COMMENT: step1[1] is the resolution and format, e.g. 320.ogg
var step2 = step1[1].split(".");
//COMMENT: step2[0] is the resoltion e.g. 720 ,step2[1] is the format (without the dot in front of the format type) e.g. ogg
var vidresolution = step2[0];
var vidformat = step2[1];
vidresolution = chosenVidQuality;
var result = upToVidName + "_q_" + vidresolution + "." + vidformat;
$('#video1').attr('src', result);
$('#video1V').attr('data-caption', vidresolution+" OGG");
$('#video1V').load();
window.alert("video1 attr src:"+document.getElementById("video1").src); //shows updated URL
}
notice that I remove $ of the variable although this is valid, an declare it with var so javascript will know that they are variables.
$(document).ready(function(){
$('#selectQuality').change(function(){
changeVidQualityFunction();
});
});
What the code do is, it will track for a change on your drop down, if change, the function will execute.
Hope this will help
I was using the Fotorama plugin and it seems that the bottom menu was causing the problem. Disabling that menu by putting div-tags around the video-tags made the function for setting resolution work. Thanks for the help and encouragement. For the bottom menu I create a simple one using link buttons that link to a similar page with the next video.
I have a hidden div containing a YouTube video in an <iframe>. When the user clicks on a link, this div becomes visible, the user should then be able to play the video.
When the user closes the panel, the video should stop playback. How can I achieve this?
Code:
<!-- link to open popupVid -->
<p>Click here to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>
<!-- popup and contents -->
<div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">
<iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40" frameborder="0" allowfullscreen></iframe>
<br /><br />
<a href="javascript:;" onClick="document.getElementById('popupVid').style.display='none';">
close
</a>
</div><!--end of popupVid -->
The easiest way to implement this behaviour is by calling the pauseVideo and playVideo methods, when necessary. Inspired by the result of my previous answer, I have written a pluginless function to achieve the desired behaviour.
The only adjustments:
I have added a function, toggleVideo
I have added ?enablejsapi=1 to YouTube's URL, to enable the feature
Demo: http://jsfiddle.net/ZcMkt/
Code:
<script>
function toggleVideo(state) {
// if state == 'hide', hide. Else: show video
var div = document.getElementById("popupVid");
var iframe = div.getElementsByTagName("iframe")[0].contentWindow;
div.style.display = state == 'hide' ? 'none' : '';
func = state == 'hide' ? 'pauseVideo' : 'playVideo';
iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
}
</script>
<p>Click here to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>
<!-- popup and contents -->
<div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">
<iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
<br /><br />
close
Here's a jQuery take on RobW's answer for use hiding /pausing an iframe in a modal window:
function toggleVideo(state) {
if(state == 'hide'){
$('#video-div').modal('hide');
document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}
else {
$('#video-div').modal('show');
document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
}
}
The html elements referred to are the modal div itself (#video-div) calling the show / hide methods, and the iframe (#video-iframe) which has the video url as is src="" and has the suffix enablejsapi=1? which enables programmatic control of the player (ex. .
For more on the html see RobW's answer.
Here is a simple jQuery snippet to pause all videos on the page based off of RobW's and DrewT's answers:
jQuery("iframe").each(function() {
jQuery(this)[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*')
});
Hey an easy way is to simply set the src of the video to nothing, so that the video will desapear while it's hidden an then set the src back to the video you want when you click on the link that opens the video.. to do that simply set an id to the youtube iframe and call the src function using that id like this:
<script type="text/javascript">
function deleteVideo()
{
document.getElementById('VideoPlayer').src='';
}
function LoadVideo()
{
document.getElementById('VideoPlayer').src='http://www.youtube.com/embed/WHAT,EVER,YOUTUBE,VIDEO,YOU,WHANT';
}
</script>
<body>
<p onclick="LoadVideo()">LOAD VIDEO</P>
<p onclick="deleteVideo()">CLOSE</P>
<iframe id="VideoPlayer" width="853" height="480" src="http://www.youtube.com/WHAT,EVER,YOUTUBE,VIDEO,YOU,HAVE" frameborder="0" allowfullscreen></iframe>
</boby>
Since you need to set ?enablejsapi=true in the src of the iframe before you can use the playVideo / pauseVideo commands mentioned in other answers, it might be useful to add this programmatically via Javascript (especially if, eg. you want this behaviour to apply to videos embedded by other users who have just cut and paste a YouTube embed code). In that case, something like this might be useful:
function initVideos() {
// Find all video iframes on the page:
var iframes = $(".video").find("iframe");
// For each of them:
for (var i = 0; i < iframes.length; i++) {
// If "enablejsapi" is not set on the iframe's src, set it:
if (iframes[i].src.indexOf("enablejsapi") === -1) {
// ...check whether there is already a query string or not:
// (ie. whether to prefix "enablejsapi" with a "?" or an "&")
var prefix = (iframes[i].src.indexOf("?") === -1) ? "?" : "&";
iframes[i].src += prefix + "enablejsapi=true";
}
}
}
...if you call this on document.ready then all iframes in a div with a class of "video" will have enablejsapi=true added to their source, which allows the playVideo / pauseVideo commands to work on them.
(nb. this example uses jQuery for that one line that sets var iframes, but the general approach should work just as well with pure Javascript if you're not using jQuery).
I wanted to share a solution I came up with using jQuery that works if you have multiple YouTube videos embedded on a single page. In my case, I have defined a modal popup for each video as follows:
<div id="videoModalXX">
...
<button onclick="stopVideo(videoID);" type="button" class="close"></button>
...
<iframe width="90%" height="400" src="//www.youtube-nocookie.com/embed/video_id?rel=0&enablejsapi=1&version=3" frameborder="0" allowfullscreen></iframe>
...
</div>
In this case, videoModalXX represents a unique id for the video. Then, the following function stops the video:
function stopVideo(id)
{
$("#videoModal" + id + " iframe")[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}
I like this approach because it keeps the video paused where you left off in case you want to go back and continue watching later. It works well for me because it's looking for the iframe inside of the video modal with a specific id. No special YouTube element ID is required. Hopefully, someone will find this useful as well.
You can stop the video by calling the stopVideo() method on the YouTube player instance before hiding the div e.g.
player.stopVideo()
For more details see here: http://code.google.com/apis/youtube/js_api_reference.html#Playback_controls
RobW's way worked great for me. For people using jQuery here's a simplified version that I ended up using:
var iframe = $(video_player_div).find('iframe');
var src = $(iframe).attr('src');
$(iframe).attr('src', '').attr('src', src);
In this example "video_player" is a parent div containing the iframe.
just remove src of iframe
$('button.close').click(function(){
$('iframe').attr('src','');;
});
Rob W answer helped me figure out how to pause a video over iframe when a slider is hidden. Yet, I needed some modifications before I could get it to work. Here is snippet of my html:
<div class="flexslider" style="height: 330px;">
<ul class="slides">
<li class="post-64"><img src="http://localhost/.../Banner_image.jpg"></li>
<li class="post-65><img src="http://localhost/..../banner_image_2.jpg "></li>
<li class="post-67 ">
<div class="fluid-width-video-wrapper ">
<iframe frameborder="0 " allowfullscreen=" " src="//www.youtube.com/embed/video-ID?enablejsapi=1 " id="fitvid831673 "></iframe>
</div>
</li>
</ul>
</div>
Observe that this works on localhosts and also as Rob W mentioned "enablejsapi=1" was added to the end of the video URL.
Following is my JS file:
jQuery(document).ready(function($){
jQuery(".flexslider").click(function (e) {
setTimeout(checkiframe, 1000); //Checking the DOM if iframe is hidden. Timer is used to wait for 1 second before checking the DOM if its updated
});
});
function checkiframe(){
var iframe_flag =jQuery("iframe").is(":visible"); //Flagging if iFrame is Visible
console.log(iframe_flag);
var tooglePlay=0;
if (iframe_flag) { //If Visible then AutoPlaying the Video
tooglePlay=1;
setTimeout(toogleVideo, 1000); //Also using timeout here
}
if (!iframe_flag) {
tooglePlay =0;
setTimeout(toogleVideo('hide'), 1000);
}
}
function toogleVideo(state) {
var div = document.getElementsByTagName("iframe")[0].contentWindow;
func = state == 'hide' ? 'pauseVideo' : 'playVideo';
div.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
};
Also, as a simpler example, check this out on JSFiddle
This approach requires jQuery. First, select your iframe:
var yourIframe = $('iframe#yourId');
//yourId or something to select your iframe.
Now you select button play/pause of this iframe and click it
$('button.ytp-play-button.ytp-button', yourIframe).click();
I hope it will help you.
RobW's answers here and elsewhere were very helpful, but I found my needs to be much simpler. I've answered this elsewhere, but perhaps it will be useful here also.
I have a method where I form an HTML string to be loaded in a UIWebView:
NSString *urlString = [NSString stringWithFormat:#"https://www.youtube.com/embed/%#",videoID];
preparedHTML = [NSString stringWithFormat:#"<html><body style='background:none; text-align:center;'><script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>var player; function onYouTubeIframeAPIReady(){player=new YT.Player('player')}</script><iframe id='player' class='youtube-player' type='text/html' width='%f' height='%f' src='%#?rel=0&showinfo=0&enablejsapi=1' style='text-align:center; border: 6px solid; border-radius:5px; background-color:transparent;' rel=nofollow allowfullscreen></iframe></body></html>", 628.0f, 352.0f, urlString];
You can ignore the styling stuff in the preparedHTML string. The important aspects are:
Using the API to create the "YT.player" object. At one point, I only had the video in the iFrame tag and that prevented me from referencing the "player" object later with JS.
I've seen a few examples on the web where the first script tag (the one with the iframe_api src tag) is omitted, but I definitely needed that to get this working.
Creating the "player" variable at the beginning of the API script. I have also seen some examples that have omitted that line.
Adding an id tag to the iFrame to be referenced in the API script. I almost forgot that part.
Adding "enablejsapi=1" to the end of the iFrame src tag. That hung me up for a while, as I initially had it as an attribute of the iFrame tag, which does not work/did not work for me.
When I need to pause the video, I just run this:
[webView stringByEvaluatingJavaScriptFromString:#"player.pauseVideo();"];
Hope that helps!
This is working fine to me with YT player
createPlayer(): void {
return new window['YT'].Player(this.youtube.playerId, {
height: this.youtube.playerHeight,
width: this.youtube.playerWidth,
playerVars: {
rel: 0,
showinfo: 0
}
});
}
this.youtube.player.pauseVideo();
A more concise, elegant, and secure answer: add “?enablejsapi=1” to the end of the video URL, then construct and stringify an ordinary object representing the pause command:
const YouTube_pause_video_command_JSON = JSON.stringify(Object.create(null, {
"event": {
"value": "command",
"enumerable": true
},
"func": {
"value": "pauseVideo",
"enumerable": true
}
}));
Use the Window.postMessage method to send the resulting JSON string to the embedded video document:
// |iframe_element| is defined elsewhere.
const video_URL = iframe_element.getAttributeNS(null, "src");
iframe_element.contentWindow.postMessage(YouTube_pause_video_command_JSON, video_URL);
Make sure you specify the video URL for the Window.postMessage method’s targetOrigin argument to ensure that your messages won’t be sent to any unintended recipient.
I have multiple video plays on a single page which I need to listen for onplay and onpause triggers, and execute custom functions which take the IDs from each of the videos tags. I need to be able to get the video id that was activated. Ive tried a few different ways, with the simple vid.onplay event works well when I know what ID is being called into. I've tried the $("video").onplay but doesn't seem to be working.
jQuery( document ).ready(function($) {
$("video").onplay = function() {
alert("The video has been paused");
};
var vid = document.getElementbyid("myVideo");
vid.onplay = function() {
alert("The video has been played");
};
});
<video class="mdia_video_player" id=myVideo poster="https://tcokchallenge.com/launch2/wp-content/uploads/2020/04/Carter.jpg?336660464" id="v0" onclick="doplayvideo(" 0")"="" controls="">
<source src="https://tcokchallenge.com/launch2/wp-content/uploads/2020/04/Carter.mp4?1222152426" type="video/mp4">
</video>```
In your first demo, it should be $("#video") to call by ID. It also says .onplay and then says that is was paused so you might want to fix that.
Ended up doing a much simpler answer, videos are within a php loop. So, I placed this within the tag
onpause="dopausevideo(<?=$vid ?>)"
onplay="doplayvideo(<?=$vid ?>)"