I have the following code which looks at a specific css class .vma_iFramePopup and from it, takes the link stored in the src. And then loads that in a modal popup.
$(document).ready(function () {
$(".vma_overlay").click(function (event) {
var $videoSrcOriginal = $(event.target).siblings('.vma_iFramePopup').attr("src");
// Check if the embedded youtube url has any attributes appended
// by looking for a '?' in the url.
// If one is found, append our autoplay attribute using '&',
// else append it with '?'.
if ($videoSrcOriginal.indexOf('?') > -1) {
var $videoSrc = $videoSrcOriginal
// when the modal is opened autoplay it
$('#vma_ModalBox').on('shown.bs.modal', function (e) {
// set the video src to autoplay
var $videoSrcAuto = $videoSrc + "&autoplay=1&mute=1";
$("#vma_video").attr('src', $videoSrcAuto);
$('body').addClass("modalyt");
})
} else {
var $videoSrc = $(".vma_iFramePopup").attr("src");
// when the modal is opened autoplay it
$('#vma_ModalBox').on('shown.bs.modal', function (e) {
// set the video src to autoplay
var $videoSrcAuto = $videoSrc + "?autoplay=1&mute=1";
$("#vma_video").attr('src', $videoSrcAuto);
$('body').addClass("modalyt");
})
}
// stop playing the youtube video when modal is closed
$('#vma_ModalBox').on('hide.bs.modal', function (e) {
$("#vma_video").attr('src', $videoSrc);
$('body').removeClass("modalyt");
})
});
});
I was informed that the videos are not playing in the modal. The modal when loaded is empty.
When I check the browser console, I am not seeing any relevant errors.
When I check the iframe inside my modal popup I see that it says
src(unknown)
in the src element:
<iframe class="embed-responsive-item" width="80%" height="80%" src(unknown) id="vma_video" allowfullscreen="" data-gtm-yt-inspected-9256558_25="true">></iframe>
I have not been able to identify why this is happening?
I 've tried fiddling on the live website with a very slight variation of your code and it seems to work:
$('.vma_overlay').on('click', function() {
var $videoSrcOriginal = $(this).siblings('.vma_iFramePopup').attr("src");
if ($videoSrcOriginal.indexOf('?') > -1) {
$('#vma_ModalBox').show();
var $videoSrcAuto = $videoSrcOriginal + "&autoplay=1&mute=1";
$('#vma_ModalBox #vma_video').attr('src', $videoSrcAuto);
$('body').addClass("modalyt");
}
});
It turns out the solution in this particular case was to replace:
$(document).ready(function () {
with:
window.onload = function () {
For some reason specific to our setup, the jquery way of getting document ready was not firing.
Related
Context: This is a Soundcloud API javascript and iframe that plays the sound of the soundcloud link when you hover over the link. The link is inputted into a table just so you know.
Problem: The problem is that when I hover over a link that I input into the table i.e say I put multiple links (each connected to a different sound) in the table but when I hover over each link they only play the sound of the first link in the table; The other links in the table does not play their appropriate sounds. Can someone help me modify the code below to fix this issue? Provide the modified code integrated with the original code below.
HTML (Iframe the src is customized to play that particular link):
<div class="clickme">
<iframe id="sc-widget" width="300" height="200" allow="autoplay"
src="https://w.soundcloud.com/player/?url=https://soundcloud.com{{-list2[1]-}}&show_artwork=true"
frameborder="0" style="display: none">
</iframe>
</div>
Javascript(Soundcloud API):
<script src="https://w.soundcloud.com/player/api.js" type="text/javascript"></script>
<script type="text/javascript">
(function () {
var widgetIframe = document.getElementById('sc-widget'),
widget = SC.Widget(widgetIframe);
widget.bind(SC.Widget.Events.READY, function () {
widget.bind(SC.Widget.Events.PLAY, function () {
// get information about currently playing sound
console.log('sound is beginning to play');
});
// get current level of volume
widget.getVolume(function (volume) {
console.log('current volume value is ' + volume);
});
// set new volume level
widget.setVolume(50);
// get the value of the current position
widget.bind(SC.Widget.Events.FINISH, function () {
// get information about currently playing sound
console.log('replaying sound');
widget.seekTo(0);
widget.play();
});
});
// Shorthand for $( document ).ready()
// A $( document ).ready() block.
$(document).ready(function () {
console.log("ready!");
var menu = document.getElementsByClassName("clickme");
for (i = 0; i < menu.length; i++) {
var list = menu[i];
var link = String(list.outerHTML)
if (link.includes('soundcloud')) {
list.addEventListener("mouseenter", function (event) {
console.log('start soundcloud');
widget.play();
});
list.addEventListener("mouseleave", function (event) {
console.log('pause soundcloud ');
widget.pause();
});
}
}
});
}());
</script>
The problem is that you're hard-coding the soundcloud player to the first iframe with an id of sc-widget by the following lines:
var widgetIframe = document.getElementById('sc-widget'),
widget = SC.Widget(widgetIframe);
To be able to play a different track on hovering, the widget needs to be populated with the proper iframe.
So these are the steps needed. If a user hovers over one of the container divs
Check if the user already hovered this specific item.
In case he did, resume the sound.
In case he didn't unbind any events from the widget if there are any, initialize the widget with the iframe, bind the required events and start playback from the beginning.
If the user leaves a container div with the mouse, stop playback if there is something playing at all.
Here's a working example:
let widget;
let currentWidget;
$(document).ready(function() {
console.log("ready!");
var menu = document.getElementsByClassName("clickme");
for (i = 0; i < menu.length; i++) {
var list = menu[i];
var link = String(list.outerHTML);
if (link.includes('soundcloud')) {
list.addEventListener("mouseenter", function(event) {
if (event.currentTarget.childNodes[1] == currentWidget) {
widget.play();
} else {
if (widget) {
widget.unbind(SC.Widget.Events.PLAY);
widget.unbind(SC.Widget.Events.READY);
widget.unbind(SC.Widget.Events.FINISH);
}
widget = SC.Widget(event.currentTarget.childNodes[1]);
widget.bind(SC.Widget.Events.READY, function() {
widget.bind(SC.Widget.Events.PLAY, function() {
// get information about currently playing sound
console.log('sound is beginning to play');
});
// get current level of volume
widget.getVolume(function(volume) {
console.log('current volume value is ' + volume);
});
// set new volume level
widget.setVolume(50);
// get the value of the current position
widget.bind(SC.Widget.Events.FINISH, function() {
// get information about currently playing sound
console.log('replaying sound');
widget.seekTo(0);
widget.play();
});
});
widget.play();
}
currentWidget = event.currentTarget.childNodes[1];
});
list.addEventListener("mouseleave", function(event) {
console.log('pause soundcloud ');
if (widget) {
widget.pause();
}
});
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://w.soundcloud.com/player/api.js" type="text/javascript"></script>
<div class="clickme" style="width: fit-content;height: fit-content;">
<iframe width="300" height="200" allow="autoplay" src="https://w.soundcloud.com/player/?url=https://soundcloud.com/crythemindlesselectron/legend-of-zelda-ocarina-of-time-thunderstruck-oc-remix&show_artwork=true" frameborder="0">
</iframe>
</div>
<div class="clickme" style="width: fit-content;height: fit-content;">
<iframe width="300" height="200" allow="autoplay" src="https://w.soundcloud.com/player/?url=https://soundcloud.com/daniel-feldkamp-2/sets/oc-remix-zelda&show_artwork=true" frameborder="0">
</iframe>
</div>
I dynamically set image and audio sources when window/document is already loaded, e.g. I set them after user performs some manipulations on the page:
// image and audio set
jQuery("#image").css('background-image', 'url(../content/icons/1/18.png)').css('backgroundPosition', '0 -40px');
var myAudio = new Audio('http://domain/content/audio/1/full-18.mp3');
myAudio.pause();
// i want this part of code be executed only when images and audio is fully loaded
myAudio.play();
Solution number 1, isn't working
jQuery("#page").load(function() {});
Solution number 2, isn't working
jQuery(window).load(function() {});
Any other idea how to this can be solved? Thank you in advance
You need to specifically target the image element to check if it has loaded.
$('#image').load(function () {
console.log('image loaded');
});
To check if the audio element is ready to be played you need to use onloadeddata.
var myAudio = new Audio('http://www.mfiles.co.uk/mp3-downloads/edvard-grieg-peer-gynt1-morning-mood.mp3');
myAudio.onloadeddata = audioIsLoaded();
function audioIsLoaded() {
console.log('audio is loaded');
}
Run the below code snippet to see this in action.
$('#image').load(function() {
alert('image loaded');
});
var myAudio = new Audio('http://www.mfiles.co.uk/mp3-downloads/edvard-grieg-peer-gynt1-morning-mood.mp3');
myAudio.onloadeddata = audioReady();
function audioReady() {
alert('audio ready');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="image" src="http://armpit-wrestling.com/wp-content/uploads/2016/06/bret-hart.jpg">
Hy,
I need to develeop a site, that will embed videos from Vimeo.
If I use VimeoAPI, can Ilisten when the video is finished? And if it finished, can I start another video from Vimeo?
Thanks, Dave.
Assuming that you have used the code provided in the Vimeo Api page you should be using the following to show an initial video:
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="custom.js" ></script>
</head>
<body>
<iframe id="vimeoplayer"
src="//player.vimeo.com/video/76979871?api=1&player_id=vimeoplayer"
width="100%" height="100%" webkitallowfullscreen mozallowfullscreen
allowfullscreen ></iframe>
<div>
<button>Play</button>
<button>Stop</button>
<p>Status: <span class="status">…</span></p>
</div>
</body>
</html>
Make sure that the iframe ID is the same with the "player_id".
Then in your custom.js file use the code from the Vimeo API page:
$(function() {
var player = $('#vimeoplayer');
var url = window.location.protocol + player.attr('src').split('?')[0];
var status = $('.status');
// Listen for messages from the player
if (window.addEventListener){
window.addEventListener('message', onMessageReceived, false);
}
else {
window.attachEvent('onmessage', onMessageReceived, false);
}
// Handle messages received from the player
function onMessageReceived(e) {
var data = JSON.parse(e.data);
switch (data.event) {
case 'ready':
onReady();
break;
case 'playProgress':
onPlayProgress(data.data);
break;
case 'pause':
onPause();
break;
case 'finish':
onFinish();
break;
}
}
// Call the API when a button is pressed
$('button').on('click', function() {
post($(this).text().toLowerCase());
});
// Helper function for sending a message to the player
function post(action, value) {
var data = {
method: action
};
if (value) {
data.value = value;
}
var message = JSON.stringify(data);
player[0].contentWindow.postMessage(data, url);
}
function onReady() {
status.text('ready');
post('addEventListener', 'pause');
post('addEventListener', 'finish');
post('addEventListener', 'playProgress');
}
function onPause() {
status.text('paused');
}
// when the video is finished
function onFinish() {
status.text('finished');
// load the next video
document.getElementById('vimeoplayer').src = "//player.vimeo.com/video/104990881?api=1&player_id=vimeovideo";
}
function onPlayProgress(data) {
status.text(data.seconds + 's played');
}
});
The code that changes the video, once the first one is finished, is inside the onFinish() function. The code inside this function changes the iframe source (src) to the one of the next video that you want to play.
You could use alternative methods of displaying another video and the above method is a very basic one just to display the requested functionality.
I wrote a jQuery Vimeo plugin a few months ago. Using this plugin, the code would be something like:
$("#somevideo").on("finish", function(){
$("#anothervideo").vimeo("play");
});
Yes, check out the player API for information on how to be notified when a video is complete, and how to start new videos https://developer.vimeo.com/player/js-api
I have a list of iframe videos in my webpage.
<iframe width="520" height="360" src="http://www.youtube.com/embed/2muxrT5_a6E" frameborder="0" allowfullscreen></iframe>
<iframe width="520" height="360" src="http://www.youtube.com/embed/2muxrT5_a6E" frameborder="0" allowfullscreen></iframe>
<iframe width="520" height="360" src="http://www.youtube.com/embed/2muxrT5_a6E" frameborder="0" allowfullscreen></iframe>
Stop all videos
I need to stop all playing iframe videos on click the link Stop all videos. How can i do that?
Try this way,
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script language="javascript" type="text/javascript">
$(function(){
$('.close').click(function(){
$('iframe').attr('src', $('iframe').attr('src'));
});
});
</script>
Reloading all iframes just to stop them is a terrible idea. You should get advantage of what comes with HTML5.
Without using YouTube's iframe_API library; you can simply use:
var stopAllYouTubeVideos = () => {
var iframes = document.querySelectorAll('iframe');
Array.prototype.forEach.call(iframes, iframe => {
iframe.contentWindow.postMessage(JSON.stringify({ event: 'command',
func: 'stopVideo' }), '*');
});
}
stopAllYouTubeVideos();
which will stop all YouTubes iframe videos.
You can use these message keywords to start/stop/pause youtube embdded videos:
stopVideo
playVideo
pauseVideo
Check out the link below for the live demo:
https://codepen.io/mcakir/pen/JpQpwm
PS-
YouTube URL must have ?enablejsapi=1 query parameter to make this solution work.
This should stop all videos playing in all iframes on the page:
$("iframe").each(function() {
var src= $(this).attr('src');
$(this).attr('src',src);
});
Stopping means pausing and setting the video to time 0:
$('iframe').contents().find('video').each(function ()
{
this.currentTime = 0;
this.pause();
});
This jquery code will do exactly that.
No need to replace the src attribute and reload the video again.
Little function that I am using in my project:
function pauseAllVideos()
{
$('iframe').contents().find('video').each(function ()
{
this.pause();
});
$('video').each(function ()
{
this.pause();
});
}
Here's a vanilla Javascript solution in 2019
const videos = document.querySelectorAll('iframe')
const close = document.querySelector('.close')
close.addEventListener('click', () => {
videos.forEach(i => {
const source = i.src
i.src = ''
i.src = source
})
})
I edited the above code a little and the following worked for me.......
<script>
function stop(){<br/>
var iframe = document.getElementById('myvid');<br/>
var iframe1 = document.getElementById('myvid1');<br/>
var iframe2 = document.getElementById('myvid2');<br/>
iframe.src = iframe.src;<br/>
iframe1.src=iframe1.src;<br/>
iframe2.src=iframe2.src;<br/>
}<br/>
</script>
$("#close").click(function(){
$("#videoContainer")[0].pause();
});
In jQuery you can stop iframe or html video, by using below code.
This will work for single or multiple video on the same page.
var videos = document.querySelectorAll('iframe');
$(".video-modal .fa-times").on("click", function () {
videos.forEach(i => {
let source = i.src;
i.src = '';
i.src = source;
});
$(".video-modal").css("display", "none");
return false;
});
})
Reload all iframes again to stop videos
Stop all videos
function stop(){
var iframe = document.getElementById('youriframe');
iframe.src = iframe.src;
}
You can modify this code with an iteration
/**
* Stop an iframe or HTML5 <video> from playing
* #param {Element} element The element that contains the video
*/
var stopVideo = function ( element ) {
var iframe = element.querySelector( 'iframe');
var video = element.querySelector( 'video' );
if ( iframe ) {
var iframeSrc = iframe.src;
iframe.src = iframeSrc;
}
if ( video ) {
video.pause();
}
};
OWNER: https://gist.github.com/cferdinandi/9044694
also posted here (by me): how to destroy bootstrap modal window completely?
This question already has answers here:
How to tell if a <video> element is currently playing?
(7 answers)
Closed 1 year ago.
I've looked through a couple of questions to find out if an HTML5 element is playing, but can't find the answer. I've looked at the W3 documentation and it has an event named "playing" but I can't seem to get it to work.
This is my current code:
var stream = document.getElementsByTagName('video');
function pauseStream() {
if (stream.playing) {
for (var i = 0; i < stream.length; i++) {
stream[i].pause();
$("body > header").addClass("paused_note");
$(".paused_note").text("Stream Paused");
$('.paused_note').css("opacity", "1");
}
}
}
It seems to me like you could just check for !stream.paused.
Check my answer at How to tell if a <video> element is currently playing?: MediaElement does not have a property that tells if it is playing or not. But you could define a custom property for it.
Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
get: function(){
return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
}
})
Now you can use it on video or audio elements like this:
if(document.querySelector('video').playing){
// Do anything you want to
}
Note : This answer was given in 2011. Please check the updated documentation on HTML5 video before proceeding.
If you just want to know whether the video is paused, use the flag stream.paused.
There is no property for a video element in getting its playing status. But there is one event "playing" which will be triggered when it starts to play. An Event called "ended" is also triggered when it stops playing.
So the solution is:
Declare one variable videoStatus.
Add event handlers for different events of video.
Update videoStatus using the event handlers.
Use videoStatus to identify the status of the video.
This page will give you a better idea about video events. Play the video on this page and see how the events are triggered.
http://www.w3.org/2010/05/video/mediaevents.html
jQuery(document).on('click', 'video', function(){
if (this.paused) {
this.play();
} else {
this.pause();
}
});
Add eventlisteners to your media element. Possible events that can be triggered are: Audio and video media events
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Html5 media events</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body >
<div id="output"></div>
<video id="myVideo" width="320" height="176" controls autoplay>
<source src="http://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4">
<source src="http://www.w3schools.com/tags/mov_bbb.ogg" type="video/ogg">
</video>
<script>
var media = document.getElementById('myVideo');
// Playing event
media.addEventListener("playing", function() {
$("#output").html("Playing event triggered");
});
// Pause event
media.addEventListener("pause", function() {
$("#output").html("Pause event triggered");
});
// Seeking event
media.addEventListener("seeking", function() {
$("#output").html("Seeking event triggered");
});
// Volume changed event
media.addEventListener("volumechange", function(e) {
$("#output").html("Volumechange event triggered");
});
</script>
</body>
</html>
Best approach:
function playPauseThisVideo(this_video_id) {
var this_video = document.getElementById(this_video_id);
if (this_video.paused) {
console.log("VIDEO IS PAUSED");
} else {
console.log("VIDEO IS PLAYING");
}
}
I encountered a similar problem where I was not able to add event listeners to the player until after it had already started playing, so #Diode's method unfortunately would not work. My solution was check if the player's "paused" property was set to true or not. This works because "paused" is set to true even before the video ever starts playing and after it ends, not just when a user has clicked "pause".
You can use 'playing' event listener =>
const video = document.querySelector('#myVideo');
video.addEventListener("playing", function () {
// Write Your Code
});
Here is what we are using at http://www.develop.com/webcasts to keep people from accidentally leaving the page while a video is playing or paused.
$(document).ready(function() {
var video = $("video#webcast_video");
if (video.length <= 0) {
return;
}
window.onbeforeunload = function () {
var htmlVideo = video[0];
if (htmlVideo.currentTime < 0.01 || htmlVideo.ended) {
return null;
}
return "Leaving this page will stop your video.";
};
}
a bit example
var audio = new Audio('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3')
if (audio.paused) {
audio.play()
} else {
audio.pause()
}
I just looked at the link #tracevipin added (http://www.w3.org/2010/05/video/mediaevents.html), and I saw a property named "paused".
I have ust tested it and it works just fine.
This is my code - by calling the function play() the video plays or pauses and the button image is changed.
By calling the function volume() the volume is turned on/off and the button image also changes.
function play() {
var video = document.getElementById('slidevideo');
if (video.paused) {
video.play()
play_img.src = 'img/pause.png';
}
else {
video.pause()
play_img.src = 'img/play.png';
}
}
function volume() {
var video = document.getElementById('slidevideo');
var img = document.getElementById('volume_img');
if (video.volume > 0) {
video.volume = 0
volume_img.src = 'img/volume_off.png';
}
else {
video.volume = 1
volume_img.src = 'img/volume_on.png';
}
}
I just did it very simply using onpause and onplay properties of the html video tag. Create some javascript function to toggle a global variable so that the page knows the status of the video for other functions.
Javascript below:
// onPause function
function videoPause() {
videoPlaying = 0;
}
// onPause function
function videoPlay() {
videoPlaying = 1;
}
Html video tag:
<video id="mainVideo" width="660" controls onplay="videoPlay();" onpause="videoPause();" >
<source src="video/myvideo.mp4" type="video/mp4">
</video>
than you can use onclick javascript to do something depending on the status variable in this case videoPlaying.
hope this helps...
My requirement was to click on the video and pause if it was playing or play if it was paused. This worked for me.
<video id="myVideo" #elem width="320" height="176" autoplay (click)="playIfPaused(elem)">
<source src="your source" type="video/mp4">
</video>
inside app.component.ts
playIfPaused(file){
file.paused ? file.play(): file.pause();
}
var video_switch = 0;
function play() {
var media = document.getElementById('video');
if (video_switch == 0)
{
media.play();
video_switch = 1;
}
else if (video_switch == 1)
{
media.pause();
video_switch = 0;
}
}
I just added that to the media object manually
let media = document.querySelector('.my-video');
media.isplaying = false;
...
if(media.isplaying) //do something
Then just toggle it when i hit play or pause.
a bit example when playing video
let v = document.getElementById('video-plan');
v.onplay = function() {
console.log('Start video')
};