Video Banner Errors - javascript

I have a site with a banner video that worked fine when we were running jquery2. After upgrading to jquery 3, the banner video no longer works. Can anyone look at the code and see what is wrong? When I look at the console in chrome, I see this error (as well as a cookie error) : jquery.min.js:2 Uncaught TypeError: e.indexOf is not a function
at S.fn.init.S.fn.load (jquery.min.js:2)
at (index):532
<video id="BannerVideo" class="Banner" muted playsinline loop oncanplaythrough="playBannerVideo()"></video>
<script>
function playBannerVideo()
{
var videoElement = document.getElementById('BannerVideo');
try
{
videoElement.play();
}
catch(err) {}
}
var basePosterURL = '/FCC/media/Images/Home2018/Banner/Banner.jpg';
var baseVideoURL = '/FCC/media/Images/Home2018/Banner/BannerVideo.mp4';
function getNameForCurrentWidth()
{
var bodyWidth = document.body.clientWidth; // $('body').width();
if (bodyWidth <= 767)
return '_Phone';
if (bodyWidth <= 990)
return '_Tablet';
return ''; // Desktop
}
var loadedWidthName;
function loadBannerVideo(posterOnly)
{
var newWidthName = getNameForCurrentWidth();
if(newWidthName == loadedWidthName)
return;
loadedWidthName = newWidthName;
var videoElement = document.getElementById('BannerVideo');
if (!videoElement.paused)
videoElement.pause();
videoElement.src = '';
videoElement.poster = addToFilename(basePosterURL, loadedWidthName);
if (posterOnly == true)
return;
setBannerVideoSrc(loadedWidthName);
}
function setBannerVideoSrc(newWidthName)
{
// don't play video if in design or edit modes
if( $('body.DesignMode').length == 1 || $('body.EditMode').length == 1)
return;
var videoElement = document.getElementById('BannerVideo');
videoElement.src = addToFilename(baseVideoURL, newWidthName);
videoElement.load();
}
// load poster as soon as possible
$(function() // document.ready
{
loadBannerVideo(true);
});
// load and play video after everything else loads
$(window).load(function()
{
setBannerVideoSrc(loadedWidthName);
});
var resizeTimeout;
$(window).resize(function()
{
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(resizeEnd, 200);
});
function resizeEnd()
{
loadBannerVideo();
}
</script>

According to this article with the same error, the load(), error() and toggle() event listeners are deprecated. Meaning you're using out of date code that isn't supported by jQuery no more.
Analyzing your code I see that you use the load() event listener. The fix here would be to use the on to listen to the load event.
$(window).on('load', function() {
// ...
});
But your code uses so little jQuery and way more vanilla JavaScript that it makes little sense to use jQuery at all. I'd recommend that you ditch it if you don't use it anywhere else. In case you do, the snippet below is the equivalent of what you posted, but without jQuery.
function playBannerVideo() {
var videoElement = document.getElementById("BannerVideo");
try {
videoElement.play();
} catch (err) {}
}
var basePosterURL = "/FCC/media/Images/Home2018/Banner/Banner.jpg";
var baseVideoURL = "/FCC/media/Images/Home2018/Banner/BannerVideo.mp4";
function getNameForCurrentWidth() {
var bodyWidth = document.body.clientWidth;
if (bodyWidth <= 767) return "_Phone";
if (bodyWidth <= 990) return "_Tablet";
return ""; // Desktop
}
var loadedWidthName;
function loadBannerVideo(posterOnly) {
var newWidthName = getNameForCurrentWidth();
if (newWidthName == loadedWidthName) return;
loadedWidthName = newWidthName;
var videoElement = document.getElementById("BannerVideo");
if (!videoElement.paused) videoElement.pause();
videoElement.src = "";
videoElement.poster = addToFilename(basePosterURL, loadedWidthName);
if (posterOnly == true) return;
setBannerVideoSrc(loadedWidthName);
}
function setBannerVideoSrc(newWidthName) {
// don't play video if in design or edit modes
if (document.querySelector("body.DesignMode").length == 1 || document.querySelector("body.EditMode").length == 1)
return;
var videoElement = document.getElementById("BannerVideo");
videoElement.src = addToFilename(baseVideoURL, newWidthName);
videoElement.load();
}
// load poster as soon as possible
loadBannerVideo(true);
// load and play video after everything else loads
window.addEventListener('load', function() {
setBannerVideoSrc(loadedWidthName);
});
var resizeTimeout;
window.addEventListener('resize', function () {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(resizeEnd, 200);
});
function resizeEnd() {
loadBannerVideo();
}

Related

TypeError: player.bind is not a function - jQuery

I cant seem to get this to work, all I am trying to do is make it so that this div's width increases as the audio player is playing so it acts as a progress bar. Everytime I run the script I get this in the console:
TypeError: player.bind is not a function
Here is my Javascript:
var player = document.getElementById('audio_player');
var progress = document.getElementsByClassName('progress-bar');
$(".play_btn").click(function() {
if(player.paused) {
player.play();
} else {
player.pause();
}
$(this).toggleClass('pause');
});
$(function() {
var check,
reached25 = false,
reached50 = false,
reached75 = false;
player.bind("play", function(event) {
var duration = player.get(0).duration;
check = setInterval(function() {
var current = player.get(0).currentTime,
perc = (current / duration * 100).toFixed(2);
if (Math.floor(perc) >= 25 &&! reached25) {
console.log("25% reached");
reached25 = true;
}
console.log(perc);
}, 500);
});
player.bind("ended pause", function(event) {
clearInterval(check);
});
});
You should use jQuery wrapper when call jquery methods on elements:
$(player).bind...

Is JS 'load' event on script guarantee full script loading?

I had a trouble with script element async loading guarantees.
When 'load' callback was called on a page with a lot of other scripts, the global variable, which should be defined in external script, was not yet available. On the other hand, after some timeout it became visible. You can see example of how I am doing it:
function async(u, c) {
var d = document, t = 'script',
o = d.createElement(t),
s = d.getElementsByTagName(t)[0];
o.async = true;
o.src = '//' + u;
if (c) { var once = false;
o.addEventListener('load', function (e) { if (!once) { once = true; c(null, e); }}, false);
o.onreadystatechange = function () {
//for IE <= 8
if (this.readyState == "complete" || this.readyState == "loaded") {
if (!once) { once = true; c(null, e); }
}
}; }
s.parentNode.insertBefore(o, s);
};
async("cdnjs.cloudflare.com/ajax/libs/ifvisible/1.0.6/ifvisible.min.js", function() {
var f = function() {
var activeSent = false;
// We detected that sometimes ifvisible is actually undefined !!!
if (typeof ifvisible != 'undefined') {
ifvisible.on('wakeup', function () {
if (!activeSent) {
activeSent = true;
console.log("I detected this move.")
}
});
ifvisible.idle();
} else {
console.log("not init.")
}
};
f();
});
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<p id="me">
Just move on ME with your mouse
</p>
My question - is there a strong or relaxed guarantee that after 'load' callback is invoked, the script was actually fully loaded on the page? Thank you.

check if images not exist on load change src

I'm trying to change my image size with javascript to be 500x375 instead of 130x98. If there is no 500x37 for that image, than I would like it to fallback to 130x98.
So far, I have the code below. It changes my images to 500x375, but the ones that do not have that size it appears broken instead of falling back to 130x98. Any ideas on how to fix this?
function ImageExists(selector) {
var imageFound = $(selector);
if (imageFound.height() === 0) {
console.log('no height');
return false;
}
return true;
}
$('div.photo > a > img').each(function(k, v) {
var x = v.src;
v.src = x.replace('130x98', '500x375');
if (!ImageExists(v)) {
console.log(v.src);
v.src = x.replace('500x375', '130x98')
}
});
You can try this code
$(document).ready(function(){
var src1 = '130x98';
var src2 = '500x375';
$('div.photo > a > img').each(function(){
var changeSrc;
var Image = $(this);
var GetSrc = $(this).attr('src');
Image.error(function() {
if(GetSrc.indexOf(src1) !== -1 ){
changeSrc = GetSrc.replace(src1 , src2);
}else if(GetSrc.indexOf(src2) !== -1 ){
changeSrc = GetSrc.replace(src2 , src1);
}
Image.attr("src", changeSrc);
});
})
});
DEMO
Are you missing semicolon in v.src = x.replace('500x375', '130x98'):in this line??
try putting alert();function in which line you doubted... alert(); will not work if any previous line is in error
$('div.photo > a > img').each(function (k, v) {
var x = v.src;
v.src = x.replace('130x98', '500x375');
if (!ImageExists(v)) {
console.log(v.src);
v.src = x.replace('500x375', '130x98');
};
How about trying the on error event instead of your ImageExists method:
$("img").error(function () {
//load in your default image dimensions.
});
When there's an error loading the image this will be triggered.
You might also want to unbind this event the first time it us run in case it continuously loops.

Functions are not working in js prototype

I have developed a jQuery plugin with prototypal inheritance.But functions are only working for main init() function and other prototypes are not working.
My main function is
function Mynav(){
....
}
Mynav.prototype.linkBehaviour = function(){
$('.nav-menu li a').on('click', function(e) {
if ($(this).attr('href') !== '#') {
var link = $(this).attr('href');
$('#preloader').removeClass('fadeOut').addClass('fadeIn').fadeIn('slow');
setTimeout(function() {
window.location = link;
}, 1500)
} else if ($(this).attr('href') == '#') {
e.preventDefault();
}
});
}
Mynav.prototype.verticalConverter = function(){
if (verticalNavOn) {
if(!verticalLive){
menuConverter();
verticalLive = true;
}
}
$(window).on('load resize', function(){
width = $(window).width();
if(width < 959){
if(!verticalLive){
menuConverter(); //This is a function also available with Mynav.prototype.menuConverter
header.removeAttr('style');
verticalLive = true;
}
} else{
convertHorizontal(); // Its also a function available
$('.header-fixed').attr('style',headerAttr);
verticalLive = false;
}
});
}
function init(){
new Mynav();
}
init();
In the upper codes linkBehaviour and verticalconverter is not working if i place linkBehaviour function in the main Mynav() it works then but not working in individual.
And i don't actually know about load/resize works with prototype or not .
Can any one help About the above two functions?
function Mynav(){
this.verticalNavOn = false;
}
Mynav.prototype.linkBehaviour = function(){
$('.nav-menu li a').on('click', function(e) {
if ($(this).attr('href') !== '#') {
var link = $(this).attr('href');
$('#preloader').removeClass('fadeOut').addClass('fadeIn').fadeIn('slow');
setTimeout(function() {
window.location = link;
}, 1500)
} else if ($(this).attr('href') == '#') {
e.preventDefault();
}
});
}
/* --------------------------------------------------------------------------------------------------------
* I believe that is in trouble when the RESIZE happens.
*
* To make the BIND (on), you must pass the own plugin AHEAD. To be used in the event when it happens.
* --------------------------------------------------------------------------------------------------------
*/
Mynav.prototype.verticalConverter = function(){
var self = this;
if (self.verticalNavOn) {
if(!self.verticalLive){
self.menuConverter();
self.verticalLive = true;
}
}
// parse THIS plugin for EVENT
$(window).on('load resize', {self: self}, function(e){
// get SELF PLUGIN
var self = e.data['self'];
width = $(window).width();
if(width < 959){
if(!self.verticalLive){
self.menuConverter(); //This is a function also available with Mynav.prototype.menuConverter
header.removeAttr('style');
self.verticalLive = true;
}
} else{
self.convertHorizontal(); // Its also a function available
$('.header-fixed').attr('style',headerAttr);
self.verticalLive = false;
}
});
}
function init(){
var x = new Mynav();
// focing start function for tests
x.verticalConverter();
}
init();
See full changes HTML and JS in: http://jsbin.com/ricaluredi/3

Youtube api does not load on firefox

I have the following code snippet that controls an embedded youtube player. It works great on Chrome and Safari but not on Firefox.
jsfiddle : http://jsfiddle.net/fuSSn/4/
Code from my app:
the iframe:
<div class="tubeframe" id="video-frame-155" style="">
<iframe title="YouTube video player" width="350" height="262" src="http://www.youtube.com/embed/hc5xkf9JqoE?HD=1;rel=0;showinfo=0;autohide=1" frameborder="0" allowfullscreen="" id="video-frame-155-frame"></iframe>
</div>
my javascript:
var source_tag = document.createElement("script");
var first_source_tag = document.getElementsByTagName("script")[0];
first_source_tag.parentNode.insertBefore(source_tag, first_source_tag);
// This function will be called when the API is fully loaded
function onYouTubeIframeAPIReady() {
YT_ready(true)
console.log("api loaded! yikes")
}
function getFrameID(id){
var elem = document.getElementById(id);
if (elem) {
if(/^iframe$/i.test(elem.tagName)) return id; //Frame, OK
// else: Look for frame
var elems = elem.getElementsByTagName("iframe");
if (!elems.length) return null; //No iframe found, FAILURE
for (var i=0; i<elems.length; i++) {
if (/^https?:\/\/(?:www\.)?youtube(?:-nocookie)?\.com(\/|$)/i.test(elems[i].src)) break;
}
elem = elems[i]; //The only, or the best iFrame
if (elem.id) return elem.id; //Existing ID, return it
// else: Create a new ID
do { //Keep postfixing `-frame` until the ID is unique
id += "-frame";
} while (document.getElementById(id));
elem.id = id;
return id;
}
// If no element, return null.
return null;
}
// Define YT_ready function.
var YT_ready = (function(){
var onReady_funcs = [], api_isReady = false;
return function(func, b_before){
if (func === true) {
api_isReady = true;
while(onReady_funcs.length > 0){
// Removes the first func from the array, and execute func
onReady_funcs.shift()();
}
}
else if(typeof func == "function") {
if (api_isReady) func();
else onReady_funcs[b_before?"unshift":"push"](func);
}
}
})();
var video = function ( videoid, frameid) {
var player;
var that;
var seconds;
var duration;
var stateChangeCallback;
var update_play = 0;
return {
setOnStateChangeCallback: function(callback) {
stateChangeCallback = callback;
},
getCurrentTime: function() {
return player.getCurrentTime();
},
getPlayer: function () {
return player;
},
getVideoFrameId: function () {
return "video-frame-" + videoid;
},
initVideo: function (second) {
console.log("initing")
that = this;
YT_ready(function(){
var frameID = getFrameID("video-frame-" + videoid);
console.log("creating player")
console.log(frameID)
if (frameID) { //If the frame exists
console.log("frame exists")
player = new YT.Player(frameID, {
events: {
"onStateChange": that.stateChange
}
});
console.log("Player Created!");
if (second) {
console.log(second)
setTimeout(function() { console.log("seek to"); player.seekTo(second, false); player.stopVideo()}, 1000);
}
}
});
},
stateChange: function (event) {
console.log("event.data = ", event.data);
switch(event.data) {
case YT.PlayerState.PLAYING:
{
if (stateChangeCallback)
stateChangeCallback("play", player.getCurrentTime(), player.getDuration());
onsole.log("play");
}
break;
case YT.PlayerState.PAUSED:
case YT.PlayerState.CUED:
case YT.PlayerState.ENDED:
{
if (stateChangeCallback)
stateChangeCallback("pause", player.getCurrentTime(), player.getDuration());
console.log("pause");
}
break;
}
},
pauseVideo: function () {
player.stopVideo();
console.log('player.stopVid()');
},
seekTo: function(second) {
player.seekTo(second, false);
}
};
};
function onStateChange(vid, action, second, total) {
if (Videos[vid]) {
console.log( (second / total) * 100);
}
};
$(document).ready(function () {
var Videos = {};
logger.info("heyyy")
var videoId=155;
//if (videoId) {
Videos[videoId] = video(videoId, 155);
console.log(Videos[155])
Videos[155].initVideo();
Videos[155].setOnStateChangeCallback(function(action, second, total) {
onStateChange(155, action, second, total);
});
//}
Videos[155].seekTo(1000, false);
onStateChange(155, "start", 0, 0);
});
I know that the required script tags are being added, I can test that from console. I also know that onYouTubePlayerAPIReady() is actually called. But I still receive errors like
TypeError: player.stopVideo is not a function
When I run the three lines that adds the source tag again from the web console on firefox, the api seems to load and everything starts working again.
I have been struggling with this for days and I really need help figuring out what might be wrong. If it helps my application is developed in ruby on rails but I don't think this is relevant information.
Thanks
There is no problem with the above code. My video was loaded in a bootstrap modal. Modal's hide property would make it invisible to firefox and firefox would not load the api at all. So I removed the modal hide class and instead of display:none I used item.css("visibility", "visible"); and item.css("visibility", "hidden"); which made firefox load the api.

Categories