How to play/pause video depending on visibility with jQuery - javascript

I want one or more videos to play/pause depending on whether or not they're in the viewport.
I understand this can be achieved with jQuery (and plugins), so I've tried using the isInViewport plugin along with the following code, but I receive the error shown below.
HTML
<script src="scripts/jquery.js"></script>
<script src="scripts/isInViewport.js"></script>
[...]
<video id="video1" src="file.mp4" width="50%"></video>
[...]
<script src="scripts/script.js"></script>
JS
var $video = document.getElementsByTagName("video1");
if ($video.is(":in-viewport")) {
$video.play();
} else {
$video.pause();
};
Console
TypeError: $video.is is not a function

try
$('video').each(function() {
if ($(this).is(":in-viewport")) {
$(this)[0].play();
} else {
$(this)[0].pause();
}
}
);

Related

Video ended function not working on mobile

I'm trying to make an image appear when the video reaches the end but it's not working and for now I have this code:
// Change image to video on click(working)
$('#image').click(function() {
video = '<video id="video" muted autoplay poster="/img.png" controls style="width: 100%; height: auto; z-index: 999999;"><source src="/video.m4v"></video>';
jQuery(this).replaceWith(video);
});
// Detect end of video(not working)
$('video').on('ended', function() {
alert("End of te video!");
});
The alert is not popping out, keep in mind that this code works fine on desktop, but not on mobile, any suggestion would be appreciated,
Thanks!
You need to create a new EventListener for the ended events
Example:
video.addEventListener('ended', function(){
//Your Code goes here
})
success: function (video, domObject) {
// add event listener
YourMediaElement.addEventListener('ended', function(e) {
//Do Stuff here
}, false);
i copied the code from the below link checck that for more info...
How to call a function on video end ? (HTML5 and mediaelementjs)

How to run code after an image has been loaded using JQuery

I'm trying to load an element only after the img element has been loaded, but I've tried everything I can think of and nothing is working. Right now I'm trying to see where the code stops working and I found that the alert I set up isn't running after the line I need the code to execute from.
$img = $('#picture');
function bubbleOnLoad() {
$(document).ready(function() {
$img.load(function(){
alert('document loaded')
$('#left-bubble').show();
})
})
The $img is defined within a function. The alert works at the document.ready line but not after the $img.load. I have tried to add eventlisteners, jquery .on, .load, and a bunch of others. I'm also calling the function to run within my init function. Can someone explain to me why nothing is working?
function choosePic()
$('.speechbubble').hide();
$('#picture').remove();
var randomNum = Math.floor(Math.random() * samplePics.length);
var img = new Image();
img.onload = function() {
$('.playing-field').prepend(img);
handleImageLoad();
}
img.src = samplePics[randomNum];
img.id = "picture";
}
var samplePics =
"assets/images/barack-obama.jpg",
"assets/images/donald-trump_3.jpg",
"assets/images/dt-2.jpg",
"assets/images/bill-clinton.jpg",
"assets/images/Rose-Byrne.jpg",
"assets/images/pic.jpeg",
"assets/images/priest.jpg",
"assets/images/tb.jpg",
"assets/images/test.jpg",
"assets/images/amy-poehler.jpg",
"assets/images/stephen-colbert.jpg",
"assets/images/aziz-ansari.jpg"
];
You had some syntax errors in your code which I corrected and came up with this:
function bubbleOnLoad() {
$img = $('#picture');
$img.load(function () {
alert('document loaded');
$('#left-bubble').show();
});
}
$(document).ready(function () {
bubbleOnLoad();
});
Here is the JSFiddle demo
In you code you are not even telling the browser it's supposed to run a code after image load. you should do something like this:
$(function(){
// DOM Content is ready, let's interact with it.
$('#picture').attr('src', 'image.jpg').load(function() {
// run code
alert('Image Loaded');
});
});
Also according to docs a common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache
Try this jQuery plugin waitForImages
https://github.com/alexanderdickson/waitForImages
//Javascript/jQuery
$(document).ready(function(){
var counter = 0,totalImages= $('#preloader').find('img').length;
$('#preloader').find('img').waitForImages(function() {
//fires for all images waiting for the last one.
if (++counter == totalImages) {
$('#preloader').hide();
yourCallBack();
}
});
});
/*css*/
#preloader{
position:absolute;
top:-100px;/*dont put in DOM*/
}
#preloader > img{
width:1px;
height:1px;
}
<!--HTML [add the plugin after jQuery] -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.waitforimages/1.5.0/jquery.waitforimages.min.js" ></script>
<!--HTML [after body start] -->
<div id=preloader>
<img src="1.jpg" />
<img src="2.jpg" />
<img src="3.png" />
<img src="4.gif" />
<img src="5.jpg" />
</div>
You can only access the HTML element after it was created in DOM.
Also you need to check if the image was loaded before showing.
Thus your code need to look something as below:
$(document).ready(function() {
bubbleOnLoad();
});
function bubbleOnLoad() {
var newSrc = "https://lh5.googleusercontent.com/-lFNPp0DRjgY/AAAAAAAAAAI/AAAAAAAAAD8/Fi3WUhXGOY0/photo.jpg?sz=328";
$img = $('#picture');
$img.attr('src', newSrc) //Set the source so it begins fetching
.each(function() {
if(this.complete) {
alert('image loaded')
$('#left-bubble').show();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="left-bubble" style="display:none">
<img id="picture"/>
</div>

JWPlayer handle youtube errors

I would like to handle the youtube errors in the JWPlayer, so in case the video doesn't exists or is not available for the country show a message on the player, or with javascript, i am doing something like this...
var options = {
height: 330,
},
flashplayer: '/player.swf',
width: 560,
events:{
onError:function(obj){
alert('ERROR'+obj);
}
} ,
debug: 'console'
};
jwplayer("player").setup(options);
jwplayer("player").play();
but its not getting inside from the onError event, even though the video doesnt even exist... and i can see in the console.. LOG (Error loading preview image: Error #2036)
In the case of youtubes restriction country i cannot even see that in the console.
In any case the video just show the loading animation, which it makes belieave the user that it can be load in any time, which its not true.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<script type="text/javascript" src="#{facesContext.externalContext.requestContextPath}/assets/jwplayer.min.js"></script>
<script type="text/javascript" src="#{facesContext.externalContext.requestContextPath}/assets/swfobject.js"></script>
<div id="player"></div>
</body>
<script type="text/javascript">
//<![CDATA[
window.onload=createPlayer();
function createPlayer() {
var flashvars = {
file:"http://www.youtube.com/watch?v=pnEHsUWFuNM",
autostart:"true"
}
var params = {
allowfullscreen:"true",
allowscriptaccess:"always"
}
var attributes = {
id:"player1",
name:"player1"
}
swfobject.embedSWF("#{facesContext.externalContext.requestContextPath}/assets/player.swf", "player", "320", "196", "9.0.115", false, flashvars, params, attributes);
}
function loadPlayer() {
var options = {
height: 325,
flashplayer: '#{facesContext.externalContext.requestContextPath}/assets/player.swf',
width: 560,
events:{
onError:function(error){
alert('Error loading your link, please try another one');
}
} /* ,
debug: 'console'*/
};
options.file = 'http://www.youtube.com/watch?v=pnEHsUWFuNM';
options.events.onReady= function(){
jwplayer("player").play();
};
jwplayer("player").setup(options);
}
//]]>
</script>
loadPlayer to try with jwplayer.js and the createPlayer directly from SWFObject... that video exist just that it shouldnt be shown in germany, still its trying to load it.
and if i set any other unexisting URL let say "http://www.youtube.com/watch?v=ABC" still keeps trying to load the unexisting video.
It looks like JW5 doesn't support catching YouTube errors. However, the following setup with JW6 works:
<!DOCTYPE html>
<html>
<head>
<title>YouTube Test Page</title>
<script type="text/javascript" src="http://www.longtailvideo.com/jwplayer/jwplayer.js"></script>
</head>
<body>
<div id="player"></div>
<script type="text/javascript">
jwplayer("player").setup({
file: "https://www.youtube.com/watch?v=ABCD",
events:{
onError: function() {
jwplayer().load({file: "http://content.longtailvideo.com/videos/flvplayer.flv",duration: "27"});jwplayer().play()
}
}
});
</script>
</body>
</html>

Dynamically loading a script changes its behaviour

I wanted paperjs to load after a button is pressed to turn on animations but it seems the paperscript doesn't work if paper is loaded after page load.
If you comment out the setTimeout and uncomment the direct $.getScript - paperjs will fire the alert('hi'). I don't get it.
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function () {
var paperUrl = 'http://cdnjs.cloudflare.com/ajax/libs/paper.js/0.22/paper.js';
$("#jq").text("jQuery is now loaded.")
var lateLoad = function() {
$.getScript(paperUrl, function() {
$("#pp").text("Paperjs is now loaded.");
});
};
//setTimeout(lateLoad, 100);
$.getScript(paperUrl, function() {
$("#pp").text("Paperjs is now loaded.");
});
});
</script>
</head>
<body>
<script type="text/paperscript" canvas="myCanvas">
$('body').css({"background-color": "#999"});
alert('hi!');
</script>
<p id="jq">jQuery NOT loaded yet.</p>
<p id="pp">Paperjs NOT loaded yet.</p>
</body>
</html>
I'm using Chrome 23.0.1271.97 m on Windows 7 x64. Anybody have an idea what's going on here?
I think I figured out a workaround as well - paper.PaperScript.load() or to elaborate:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function () {
$("#jq").text("jQuery is now loaded.")
var paperUrl = 'http://cdnjs.cloudflare.com/ajax/libs/paper.js/0.22/paper.js';
var lateLoad = function() {
$.getScript(paper_url, function() {
$("#pp").text("Paperjs is now loaded.");
paper.PaperScript.load(); // <-- The fix!
});
};
setTimeout(lateLoad, 1000);
//$.getScript(paperUrl, function() {
// $("#pp").text("Paperjs is now loaded.");
//});
});
</script>
</head>
<body>
<script type="text/paperscript" canvas="myCanvas">
$('body').css({"background-color": "#999"});
alert('hi!');
</script>
<p id="jq">jQuery NOT loaded yet.</p>
<p id="pp">Paperjs NOT loaded yet.</p>
</body>
</html>
That causes paperscript to scan for all the paperscripts. I found it at https://github.com/paperjs/paper.js/blob/master/src/core/PaperScript.js#L270 while googling for "paperscript" in the github repo. Though it still doesn't explain why paper doesn't do the load() on its own when dynamically loaded.
EDIT - I understand what went wrong. It's related to https://github.com/jquery/jquery/blob/master/src/core.js#L768 because paperjs doesn't check if the window loaded event had already fired i.e document.readyState === "complete". I submitted a pull request to paperjs https://github.com/paperjs/paper.js/pull/156
I think it is easier to load it via require.js. All you need is a require.config object, defined in e.g. main.js:
requirejs.config({
paths : {
'jquery' : "path/to/jquery"
'paper' : "path/to/paper"
},
shim: {
'jquery' : {
exports: 'jQuery'
},
'paper' : {
exports: 'paper'
}
}
});
You will need to load require.js with the above config via the data-main attribute:
<script data-main="scripts/main.js" src="scripts/require.js"></script>
Then you define a module (e.g. 'paperStuff') where your paper logic will be:
define(['jquery', 'paper'], function($, paper) {
// do some cool stuff
});
When you want to load your paperStuff, you just do
var paperStuff = require('paperStuff');
...
Move your paperscript code into an external file (i.e. pstest.js) and modify your lateLoad to:
var lateLoad = function() {
$.getScript('http://cdnjs.cloudflare.com/ajax/libs/paper.js/0.22/paper.js',
function() {
$("#pp").text("Paperjs is now loaded.");
$.getScript("pstest.js");
} )
}

YouTube API — not firing 'onYouTubePlayerReady()'

From what I've read, this is how I should setup the YouTube API:
<!DOCTYPE html>
<html lang="en">
<head>
<meta content='text/html;charset=UTF-8' http-equiv='content-type' />
<title>Youtube Player</title>
<script src="jquery.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
function onYouTubePlayerReady(id) {
console.log("onYouTubePlayerReady() Fired!");
var player = $("#youtube_player").get(0);
}
var params = { allowScriptAccess: "always" };
var atts = { id: "youtube_player" };
swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1",
"youtube", "425", "356", "8", null, null, params, atts);
</script>
</head>
<body>
<div id="youtube"></div>
</body>
</html>
However, 'onYouTubePlayerReady()' doesn't fire at all, and if I manually get a reference to the player, a lot of methods are undefined; for example, cueVideoById() works, but playVideo() doesn't.
How can I fix this problem?
You need to be on a web server with your test script, as stated in the documentation:
Note: To test any of these calls, you must have your file running on a webserver, as the Flash player restricts calls between local files and the internet.
this function:
function onYouTubePlayerReady(playerid) {
console.log('readyIn');
};
don't have to be directly in head in separate script tag.
Only rule you have to keep is: don't put this function inside domready event - it has to be defined sooner.
For example in mootools I use it like this:
function onYouTubePlayerReady(playerid) {
echo('readyIn');
};
document.addEvent('domready', function() {
...
});
I have the answer, separate out this portion of the script and put it in the head in its own script tag. OMG, finally
<script type="text/javascript" language="javascript">
function onYouTubePlayerReady(playerid) {
ytp = document.getElementById('ytplayer');
ytp.mute();
};
</script>
I consider this the best way of adding a youtube video to your website with javascript. It gives you a very clear way of dealing with events. It works on a local machine, and as far as I know it works on apple devices. You can use all the events and function described in the javascript documentation for the youtube api.
<div id="player"></div>
<script>
//Load player api asynchronously.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var done = false;
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'JW5meKfy3fY',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(evt) {
evt.target.playVideo();
}
function onPlayerStateChange(evt) {
if (evt.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
source: http://apiblog.youtube.com/2011/01/introducing-javascript-player-api-for.html
<!DOCTYPE html>
had to lead the page in order for the html5 stuff to function for me in FF4
If you're embedding youtube videos like so:
<iframe src="http://www.youtube.com/embed/VIDEO_ID?jsapi=1" width="1280" height="720" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
then you should place
<script src="http://www.youtube.com/player_api"></script>
after the </iframe>. At least that's how I got it to work.
Additionally, if you're dynamically changing the [src] attribute of the iframe via jQuery or whatever to load a new video then you need to call onYouTubePlayerAPIReady() after it has loaded.
I prefer to change the [src] attribute and then:
setTimeout(onYouTubePlayerAPIReady, 500);
Just had the same issue, but for another reason. It worked in Chrome but not Firefox, and the reason was that I had a http header "Content-type: text/xml" instead of "Content-type: text/html". Serving as HTML now fires the onYouTubePlayerReady event in Firefox, too.
Just posting this in case someone stumbles on this answer from Google (like I just did when trying to find a solution).

Categories