Catch video HTML5 play/stop event - html

How can I listen to the events play/stop/pause of a HTML5 video?
I tried with the following code:
$("video").on('play',function(){
//my code here
});
but it does not work.
Alternatively I would be fine also intercept the click that stop and start the video (in fact I would prefer), but even this code not works:
$('video').on('click', function(event) {
//my code here
});
I think because often above the video element is placed a div with associated events start and stop, but I do not know how to select via jQuery or Javascript:
P.S. This code should work on pages that are composed dynamically / not generated by me, so I can not refer the elements indicating their ID or a specific class.
UPDATE
I did not realize that the page on which I was testing had a video inside an iframe.
The syntax is best suited to my needs:
doc.querySelector("video").addEventListener('play', function(e) {
//my code here
}, true);

See here:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events
So... :
$("video")[0].onplay = function () {
// Do play stuff here
};
Hope that helps!

Your first attempt should work. But you need to make sure that jQuery is actually finding video elements. You say that the page is generated dynamically, so perhaps it's possible that your code is running before the video elements are added. This would also be the case if your script is higher up in the document than the video elements (e.g., in the <head>).
Try placing the following code immediately before the code you have there and check the output:
console.log($("video"));
If the output is an empty array, then you aren't finding any video elements. Try placing your script at the very end of the page or inside a DOMContentLoaded event. Or, if another script is generating the video elements, make sure your script runs after that one.
A few other notes on your question:
There is no stop event. Here's a list of media events.
I don't think the click event is what you want. That will fire no matter where on the video the user clicks: play button, volume control, etc.
The video being placed inside a div shouldn't have any effect on these events. I'm not sure why you'd have start and end events on a div, so maybe I'm not following.

Give this a try!
//Direct
<video id="videoThis" src="blahhh.mp4" onended="yourFunction()"></videoThis>
-or-
//JavaScript (HTML5)
document.querySelector("#videoThis").addEventListener("ended",yourFunction,false);
-or-
//jQuery
$("#videoThis").bind("ended",yourFunction);

Related

I have multiple HTML 5 <Audio> tags on one page and I want ALL of them to pause when another is played

I think I need a script that will "get" all the playing HTML5 audio controls and "pause" them apart from the one the user clicks play on. I have seen and can handle simple play, pause, stop with just one audio controls but my skills fall way short of coding something to do what I'm after with multiples. audio controls is a neat solution and integrates well with my current design, I just need help making it work properly. The use case:
https://aberaeronskies.com/ page loads and nothing plays which is desired, user clicks play on a audio controls tag and the track snippet plays which is desired. User clicks on another one (there are 14) and it starts to play, trouble is, the first one is still playing which is not desired; one could click on all of them and they would all play!
The requirement is for a script or a call or whatever (I'm no coder, just doing this as freebie for a mate) that when a user clicks play on any one of the 14 tracks it pauses all other playing tracks.
I thought this was it: Pause all other players besides activated one. jQuery audio plugin for <audio> element and Play selected audio while pausing/resetting others but I'cant make them work.
It may be that this cannot be done and I need to rethink the whole presentation of multiple tracks and if so, further advice on where to look (in addition to above) would also be useful.
Thanks very much...
Ah...
This works
var curPlaying;
window.addEventListener("play", function(evt)
{
if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)
{
window.$_currentlyPlaying.pause();
}
window.$_currentlyPlaying = evt.target;
}, true);
$(function () {
$(".playback").click(function (e) {
e.preventDefault();
var song = $(this).next('audio')[0];
if (song.paused) {
if (curPlaying) {
$("audio", "#" + curPlaying)[0].pause();
}
song.play();
curPlaying = $(this).parent()[0].id;
} else {
song.pause();
curPlaying = null;
}
});
});

Play one of a set of audio clips randomly?

So I'm trying to setup a web-page where when you open it, it will play a random piece of music, and when that one finishes, it will play another directly after so you get a constant stream of music, but not in the same order every time. If this goes outside the bounds of HTML and I'm looking at for instance JavaScipt than that's fine.
I know this is probably a rather easy solution, but I'm new to HTML and trying to understand it better.
Thanks in advance if I don't get back to you soon!
This is best solved using JavaScript, which is used to add behavior to a website. HTML is primarily used to structure your site.
We can get a collection of all audio elements with the querySelectorAll function. Then we find a random element with the next line and call the play method.
var audio = document.querySelectorAll("audio");
function playRandom() {
audio[Math.floor(Math.random() * audio.length)].play()
}();
For the second part of your question, you would want to listen for the ended event. Inside the event listener function, you would then call the playRandom() function.
audio.addEventListener("ended", function() {
playRandom();
});

Mute HTML 5 video & random video load

Three part question...
I'm using http://syddev.com/jquery.videoBG/index.html for HTML 5 video background on my site. Works perfectly! However I have some additional functions I want to add on but not quite sure how to pull it off.
1_ I would like to add a button to mute/unmute audio. I'm not that great at jquery so what I'm looking for is what I need to add to the existing code to make it happen and what I need to put in the place where I want the actual button to go. I'm guessing I need to add some mute option to...
$('.bg').videoBG({
position:"fixed",
zIndex:0,
mp4:'_video/ClimbBG.mp4',
ogv:'_video/ClimbBG.ogv',
webm:'_video/ClimbBG.webm',
poster:'_images/ClimbBG.jpg',
opacity:1,
fullscreen:true,
});
Then some function/code in the spot I want the button to be?
2_ I would like to have a different random video load each time the site is loaded. Maybe even have a new video play after the first one is finished?
Example...This site loads a different video when the page is refreshed ( cabin-time.com )
3_ Not super important but I've noticed a lot of people who use video backgrounds have little dots in the video (cabin-time.con is one example). I'm guessing this is to reduce file size? Most likely done in Final Cut? How do I add this into my video and does it really reduce file size?
Thanks!!!
Unfortunately, VideoBG does not support mute, so you can't just 'add mute option' to it, you'll need to make it yourself.
Here are some points to get you started, edit the videoBG.js, to add a 'muted' attribute ( http://syddev.com/jquery.videoBG/jquery.videoBG.js )
......
// video element
var $video = $('<video/>');
$video.css('position','absolute')
.css('z-index',options.zIndex)
.attr('poster',options.poster)
.attr('muted',options.muted)
.css('top',0)
.css('left',0)
.css('min-width','100%')
.css('min-height','100%');
.......
// these are the defaults
$.fn.videoBG.defaults = {
mp4:'',
ogv:'',
webm:'',
poster:'',
autoplay:true,
loop:5,
sclae:false,
position:"absolute",
opacity:1,
textReplacement:false,
zIndex:0,
width:0,
height:0,
muted:false
Now you can add muted:true to your properties

mediaelement.js play/pause on click controls don't work

I need to play and pause the video player if any part of the video is clicked, so I implemented something like:
$("#promoPlayer").click(function() {
$("#promoPlayer").click(function() {
if(this.paused){
this.play();
} else {
this.pause();
}
});
...but now the controls of the video won't pause/play.
You can see it in action here(http://175.107.134.113:8080/). The video is the second slide on the main carousel at the top.
I suspect I'm now getting 2 onclick events one from my code above and a second on the actual pause/play button.
I don't understand how the actual video controls work, because when I inspect the element, I just see a tag. If I could differentiate the controls, then perhaps I might have figured out a solution by now.
Anyone know how I should have done this, or is my solution ok. If my solutions ok, how do I intercept a click on the control, so that I only have one click event to pause / play?
If you look on the media element home page, they have a big play button, complete with mouseOver, but I can't see how they have done that? Can someone else help?
The controls of the browser's native player are not individual DOM elements so I don't believe there's a way to identify them.
My suggestion would be to create an invisible div which covers the player but not the controls, and bind your logic to that.
Ok, I was being an idiot. I hadn't initialised the MediaElement player:
$(document).ready(function(){
$("#promoPlayer").mediaelementplayer({
features: ['playpause','progress','current','duration','tracks','volume','fullscreen'],
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false
});
});
Which mean't that what I thought was MediaElement, was actually just my browser's native support for the tag...
As expected MediaElement does of course give you such things as being able to click the whole video frame and have the video start for free...
The player should already play/pause on click, but if you want to attach events it's best to do so within the success handler:
$(document).ready(function(){
$("#promoPlayer").mediaelementplayer({
success: function(media, domElement, player) {
$('#somebutton').on('click', function() {
media.play();
});
}
});
});

Stop img tags from flickering when re-rendering with JavaScript

Our web app is built entirely in JS.
To make it snappy we cache resources (models) between page views and reload the resource when you view a page.
Our flow is like this:
The user is in ViewA
The user switches to ViewB
We use the cached resource to render ViewB
We start a fetch for resource
When the resource is fetched we render again
This has a nasty drawback of causing <img> tags to flicker, ever if they are the same.
The problem is that Backbone.js, which we use, doesn't tell us if anything changed when fetching a collection, just that it was fetched.
Here's a quick demo of what I mean: http://jsfiddle.net/p7DdG/
It only happens in webkit and with <img> tags, not with background images as you can see.
We think it's kinda ugly to use background-image instead of a proper img tag.
Is there any solution to this?
The problem is gone in Chrome 19, problem solved :)
Not knowing exactly how the URL of each image is being built I'm not certain this will work, but could you check the src attribute of each image tag against the one you are replacing it with before doing the replace?
e.g.
var newImageSrc = "http://www.google.com/intl/en_com/images/srpr/logo3w.png";
if (newImageSrc != $("img").attr("src")) {
$('img').replaceWith('<img src="'+newImageSrc +'">');
}
Alternatively - load the image offscreen, and attach an event handler to the onload event of the image, which moves the image to the current image's parent tag, and remove the old one.
e.g.
var oldImage = $("#oldImageId");
var newImageSrc = "http://www.google.com/intl/en_com/images/srpr/logo3w.png";
var newImage = new Image();
$(newImage).load(function (event) {
$(oldImage).parent().append(newImage);
$(oldImage).detach();
});
$(newImage).attr("src", newImageSrc);
I ran into the same problem and noticed that sometimes images do flicker and sometimes don't. Even in latest Chrome (v33 as of now).
For posterity, flickering happens with uncached images.
In my case, Cache-Control: public, max-age=31536000 totally eliminated it.