Global JS var not being seen - javascript

My company bought a timeline plugin and it throws an error in every browser. It still works in Chrome and FireFox but is totally busted in IE (v11)
The JS error has to do with a global variable (defined in audio.min.js) that is not being seen in a following JS file (jquery.timeline.js).
The JS files in the HTML page are listed with the JS file with the global variable, first, followed by the other JS file, where the error is being generated so that all looks right.
Not sure what could cause this...
<script type="text/javascript" src="/Timeline/js/jquery/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="/Timeline/js/audiojs/audio.min.js"></script>
<script type="text/javascript" src="/Timeline/js/jquery.timeline.js"></script>
Here is the line that causes the error:
audio.prettyPaused = 0;
The errors:
SCRIPT1028: Expected identifier, string or number
Unable to set property 'prettyPaused' of undefined or null reference
Uncaught TypeError: Cannot set property 'prettyPaused' of undefined
The var "audio" is defined in a separate JS file (audio.min.js), right at the top of the file:
//SHARED VARIABLE TO INTERACT WITH VIDEO & PRETTYPHOTO
var audio;
Here is the line in context:
//HTML5 AUDIO PLAYER
audiojs.events.ready(function() {
var as = audiojs.createAll({
autoplay: true,
loop: true
});
audio.prettyPaused = 0;
});
Even More Context
//jquery.timeline.js
jQuery(document).ready(function() {
jQuery.myTimeline();
});
(function($) {
// GLOBAL VARS
var preload, container, tl, vidRoll, imgRoll, readBt, viewport, images, milestones, content, bar, track, dragger, marksAmount, fadeInDelay;
// CLASS CONSTRUCTOR / INIT FUNCTION
$.myTimeline = function() {
//SETUP VARS
preload = $('.preload');
container = $('#timeline_container');
tl = $('#timeline');
vidRoll = $('.video_rollover');
imgRoll = $('.image_rollover');
readBt = $('.readmore');
viewport = $('#timeline .viewport');
images = $('#timeline .viewport .images');
milestones = $('#timeline .milestones');
content = $('#timeline .milestones .content');
bar = $('#timeline .scrollbar');
track = $('#timeline .scrollbar .track');
dragger = $('#timeline .scrollbar .track .dragger');
marksAmount = $('.marks > div').length;
fadeInDelay = parseInt(tl.attr("data-fadeInDelay"));
//CONFIG ALL ELEMENTS SIZES AND POSITIONS BASED ON HTML ATTRIBS
container.css("width", tl.attr("data-width"));
container.css("height", tl.attr("data-height"));
images.css("width", tl.attr("data-imagesWidth"));
viewport.css("height", tl.attr("data-imagesHeight"));
content.css("width", tl.attr("data-contentWidth"));
milestones.css("height", tl.attr("data-contentHeight"));
bar.css("top", tl.attr("data-imagesHeight") - tl.attr("data-draggerHeight"));
track.css("height", tl.attr("data-draggerHeight"));
dragger.css("height", tl.attr("data-draggerHeight"));
//PRELOAD & GLOBAL FADE IN
preload.delay(fadeInDelay - 500).animate({ opacity:0 }, 500, 'easeOutQuad');
container.delay(fadeInDelay).animate({ opacity:1 }, 1000, 'easeOutQuad');
//HTML5 AUDIO PLAYER
audiojs.events.ready(function() {
var as = audiojs.createAll({
autoplay: true,
loop: true
});
audio.prettyPaused = 0;
});
//PRETTYPHOTO LIGHTBOX GALLERY
$('a[data-rel]').each(function() {
$(this).attr('rel', $(this).data('rel'));
});
$("a[rel^='prettyPhoto']").prettyPhoto({social_tools:false});
//TIPSY - TOOLTIP
readBt.tipsy({ gravity: 'w', fade: true, offset: 5 });
//IMAGE ROLLOVER ICON
imgRoll.append("<span></span>");
imgRoll.hover(function(){
$(this).children("span").stop(true, true).fadeIn(600);
},function(){
$(this).children("span").stop(true, true).fadeOut(200);
});
//VIDEO ROLLOVER ICON
vidRoll.append("<span></span>");
vidRoll.hover(function(){
$(this).children("span").stop(true, true).fadeIn(600);
},function(){
$(this).children("span").stop(true, true).fadeOut(200);
});
//VIDEO THUMB STOPS MUSIC ON CLICK (IF PLAYING)
vidRoll.click(function() {
if (audio.playing) {
audio.prettyPaused = 1;
audio.pause();
} else {
audio.prettyPaused = 0;
}
});
//START DRAG IMAGES FUNCTION
startDrag(images);
//SCROLLBAR MILESTONES MARKS
for ( var i = 0; i < marksAmount; i++ ) {
current = $('#m'+i);
current.stop(true, true)
.delay(fadeInDelay + 500)
.animate({ left:current.attr("data-xpos"), opacity:1 }, 700 + 100*i, 'easeOutQuad')
.show()
.tipsy({ gravity: 's', fade: true, offset: 3, fallback: current.attr("data-label") });
};
//INIT SCROLLBAR
tl.tinyscrollbar({
wheel: 20,
mouseWheel: tl.attr("data-mouseWheel"),
size: tl.attr("data-width"),
draggerWidth: tl.attr("data-draggerWidth")
});
} // END OF CLASS CONSTRUCTOR

var audio; defines it, but doesn't initialize it. That's the problem. Nothing you've shown suggests that audio is actually initialized. My guess would be that audio and audiojs are probably intended to be the same thing, but that's a guess based on just what you provided.

Unable to set property 'prettyPaused' of undefined or null reference means that var audio has not been initialized, so it could be a global problem or just not initialized.
You say it gets created in that script - very well, add code below to make sure:
<script type="text/javascript" src="/Timeline/js/audiojs/audio.min.js">
console.log(audio);
</script>
I would suspect that's going to return "undefined" or "null". Means you have to create the object or request it somehow via that script.

Related

turn.js display option based on window width

i am trying to make a flipbook with turn.js which is awesome.
the only problem i have is that i am trying to make it so in mobies it is single page display and in desktops double page display.
it does have the option to choose when creating the flipbook in javascript
display: 'single' or display: 'double'
i managed to achive changing that when you resize the window but with the onresize jwuery event but that makes it so it triggers only when you resize the window but if you dont it is always double page...so when the browser renders the page for mobile it is as defaul double page and not single
let me post my code here
// Create the flipbook
flipbook.turn({
// Magazine width
width: 922,
// Magazine height
height: 600,
// Duration in millisecond
duration: 1000,
// Enables gradients
gradients: true,
// Auto center this flipbook
autoCenter: true,
// Elevation from the edge of the flipbook when turning a page
elevation: 50,
// The number of pages
pages: 12,
// Events
when: {
turning: function(event, page, view) {
var book = $(this),
currentPage = book.turn('page'),
pages = book.turn('pages');
// Update the current URI
Hash.go('page/' + page).update();
// Show and hide navigation buttons
disableControls(page);
},
turned: function(event, page, view) {
disableControls(page);
$(this).turn('center');
$('#slider').slider('value', getViewNumber($(this), page));
if (page==1) {
$(this).turn('peel', 'br');
}
},
missing: function (event, pages) {
// Add pages that aren't in the magazine
for (var i = 0; i < pages.length; i++)
addPage(pages[i], $(this));
}
}
});
//change from single to double page
$(window).resize(function(){
var win = $(this); //this = window
if (win.width() >= 820) { flipbook.turn('display','double');}
else {
flipbook.turn('display','single');
}
});
i hope someone can help me fix this
To make the flipbook responsive for mobile, you can add the following code, which checks if the user agent of the navigator is mobile or not.
function checkMobile() {
return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
}
And then use this in the resize of the window function.
if (!checkMobile()) { // not mobile
$('.flipbook').turn('display', 'double');
}
else {
$('.flipbook').turn('display', 'single');
}
You can use the above snippet after you have initialized the flipbook, to dynamically set the display (double, single) of the flipbook.
so hello everyone again, i managed to figure this out..
i changed the last code part from this
$(window).resize(function(){
var win = $(this); //this = window
if (win.width() >= 820) { flipbook.turn('display','double');}
else {
flipbook.turn('display','single');
}
});
to that
$(window).width(function(){
var win = $(this); //this = window
if (win.width() >= 820) { flipbook.turn('display','double');}
else {
flipbook.turn('display','single');
}
});
$(window).resize(function(){
var win = $(this); //this = window
if (win.width() >= 820) { flipbook.turn('display','double');}
else {
flipbook.turn('display','single');
}
});
it works fine both when you refresh the page and when you resize the window. I don't know if this the right way to do it but it seems to work perfectly fine
For mobile screens you have to change the screen width
here is tested and working code
if(window.innerWidth<768 && window.innerWidth >= 320) {
$('#flipbook').turn({
width:430,
height:650,
elevation:50,
inclination:50,
display: 'single',
autocenter:true,
acceleration: true,
gradients:true,
zoom:2,// you can change it as you desire
duration:50,
});
}
Here is what works for me on the mobile screen:
$('#flipbook').turn({
display: 'single',
acceleration: true,
gradients: true,
elevation:50,
when: {
turned: function(e, page) {
console.log('Current view: ', $(this).turn('view'));
}
}
});

Jquery JSON plugin colliding with slick carousel

I am relatively new to jquery but i need that script to start working properly.
I have an jquery script for reading JSON data from url. It is working by itself but when i try to load data inside slick carousel, carousel stops working. I think that the problem is inside my script. Please help!
My code:
(function($){
$.fn.scores = function() {
liveScores();
};
function liveScores() {
setTimeout(liveScores, 5000);
var jsonData = "http://url";
$.getJSON(jsonData, function(rawJsonData){
var complete =[];
//var realcatCount = rawJsonData.doc[0].data[0].realcategories.length;
for (realCat = 0; realCat <= 3; realCat ++) {
console.log(realCat);
var basePath = rawJsonData.doc[0].data[0].realcategories[realCat]
var tournament = basePath.tournaments[0].name;
var name = basePath.name;
var matchStatus = basePath.tournaments[0].matches[0].status._id;
var homeTeam = basePath.tournaments[0].matches[0].teams.home.name;
var awayTeam = basePath.tournaments[0].matches[0].teams.away.name;
var time = basePath.tournaments[0].matches[0]._dt.time;
var date = basePath.tournaments[0].matches[0]._dt.date;
var homeScore = basePath.tournaments[0].matches[0].result.home;
var awayScore = basePath.tournaments[0].matches[0].result.away;
var teamIdHome = basePath.tournaments[0].matches[0].teams.home.uid;
var teamIdHAway = basePath.tournaments[0].matches[0].teams.away.uid;
complete.push('<div class="slide-wrapper"><h2>'+tournament+'</h2><h4>'+name+'</h4><div class="score">'+homeScore+ ' vs. '+awayScore+'</div><div class="team home-team"><div class="crest crest-home" style="background:url(http://ls.betradar.com/ls/crest/big/'+teamIdHome+'.png) no-repeat center center;"></div><h3>'+homeTeam+'</h3></div><div class="team away-team"><div class="crest crest-away" style="background:url(http://ls.betradar.com/ls/crest/big/'+teamIdHAway+'.png) no-repeat center center;"></div><h3>'+awayTeam+'</h3></div><div class="overlay"></div><img class="bcg" src="images/bg-live.jpg"></div>');
}
console.log(complete);
$('#results').empty().append(complete);
});
};
})(jQuery);
This is the order i load scripts and plugins at the bottom of the page.
<script type="text/javascript" src="js/scores.js"></script>
<script>
$(document).ready(function() {
$().scores();
});
</script>
<script type="text/javascript" src="js/slick.js"></script>
<script>
$(document).ready(function(){
$('.slider').slick({
dots: true,
arrows: false,
infinite: true,
speed: 300,
slidesToShow: 1,
adaptiveHeight: true,
fade: true,
cssEase: 'linear'
});
});
</script>
First i load carousels item (JSON data) and then the slick carousel itself.
And the slick carousel works just fine until i put data from my plugin into it.
The code provided is not very good,
for instance you don't know if there are 3 realcats (0,1,2)
don't use json as a variable name, json is a notation, not an good variable name
$.getJSON(jsonData, function(rawJsonData){
var complete =[];
var realcatCount = rawJsonData.doc[0].data[0].realcategories.length;
for (realCat = 0; realCat <= (realcatCount -1); realcatCount ++) {
console.log(realCat);
var basePath = json.doc[0].data[0].realcategories[realCat]
...
The rest of your code seems ok, but not really good.
Try to walk the json path as less as needed.
this would be:
var match = basePath.tournaments[0].matches[0];
var matchStatus = match .status._id;
var homeTeam = match .teams.home.name;
What you need to do is make sure your html is there BEFORE you bind it. so first generate the carrousel items, and then perform the .slick() function
This way you would get:
// Your existingt code..
$('#results').empty().append(complete);
// AND then slick it.. Delete this code from the seperate code block in your html and move it to here..
$('.slider').slick({
dots: true,
arrows: false,
infinite: true,
speed: 300,
slidesToShow: 1,
adaptiveHeight: true,
fade: true,
cssEase: 'linear'
});
Your problem is that .slick is called BEFORE the html is there (it is derived from a web url)
first create the html, and append it
then do .slick
The resulting (working) code:
https://jsfiddle.net/aeuuymuy/12/

jquery responsive wordpress slider height change

I have a premium wordpress theme which came with a built in full page slider. It integrates nicely into my website but it displays full page and the information underneath is being lost. The slider is responsive to the window size, I'd like it to be only 60%. Please can someone help:
(function ($) {
"use strict";
$.fn.maximage = function (settings, helperSettings) {
var config;
if (typeof settings == 'object' || settings === undefined) config = $.extend( $.fn.maximage.defaults, settings || {} );
if (typeof settings == 'string') config = $.fn.maximage.defaults;
/*jslint browser: true*/
$.Body = $('body');
$.Window = $(window);
$.Scroll = $('html, body');
$.Events = {
RESIZE: 'resize'
};
this.each(function() {
var $self = $(this),
preload_count = 0,
imageCache = [];
/* --------------------- */
// #Modern
/*
MODERN BROWSER NOTES:
Modern browsers have CSS3 background-size option so we setup the DOM to be the following structure for cycle plugin:
div = cycle
div = slide with background-size:cover
div = slide with background-size:cover
etc.
*/
var Modern = {
setup: function(){
if($.Slides.length > 0){
// Setup images
for(var i in $.Slides) {
// Set our image
var $img = $.Slides[i];
// Create a div with a background image so we can use CSS3's position cover (for modern browsers)
$self.append('<div class="mc-image ' + $img.theclass + '" title="' + $img.alt + '" style="background-image:url(\'' + $img.url + '\');' + $img.style + '" data-href="'+ $img.datahref +'">'+ $img.content +'</div>');
}
// Begin our preload process (increments itself after load)
Modern.preload(0);
// If using Cycle, this resets the height and width of each div to always fill the window; otherwise can be done with CSS
Modern.resize();
}
},
preload: function(n){
// Preload all of the images but never show them, just use their completion so we know that they are done
// and so that the browser can cache them / fade them in smoothly
// Create new image object
var $img = $('<img/>');
$img.load(function() {
// Once the first image has completed loading, start the slideshow, etc.
if(preload_count==0) {
// Only start cycle after first image has loaded
Cycle.setup();
// Run user defined onFirstImageLoaded() function
config.onFirstImageLoaded();
}
// preload_count starts with 0, $.Slides.length starts with 1
if(preload_count==($.Slides.length-1)) {
// If we have just loaded the final image, run the user defined function onImagesLoaded()
config.onImagesLoaded( $self );
}else{
// Increment the counter
preload_count++;
// Load the next image
Modern.preload(preload_count);
}
});
// Set the src... this triggers begin of load
$img[0].src = $.Slides[n].url;
// Push to external array to avoid cleanup by aggressive garbage collectors
imageCache.push($img[0]);
},
resize: function(){
// Cycle sets the height of each slide so when we resize our browser window this becomes a problem.
// - the cycle option 'slideResize' has to be set to false otherwise it will trump our resize
$.Window
.bind($.Events.RESIZE,
function(){
// Remove scrollbars so we can take propper measurements
$.Scroll.addClass('mc-hide-scrolls');
// Set vars so we don't have to constantly check it
$.Window
.data('h', Utils.sizes().h)
.data('w', Utils.sizes().w);
// Set container and slides height and width to match the window size
$self
.height($.Window.data('h')).width($.Window.data('w'))
.children()
.height($.Window.data('h')).width($.Window.data('w'));
// This is special noise for cycle (cycle has separate height and width for each slide)
$self.children().each(function(){
this.cycleH = $.Window.data('h');
this.cycleW = $.Window.data('w');
});
// Put the scrollbars back to how they were
$($.Scroll).removeClass('mc-hide-scrolls');
});
}
}
Thanks in advance. James
Generally, the themes are very customizable on the admin panel. So, you should check it out before you changing it by hand.
If you dont find for customization on the admin panel (and on the theme developer page), as you may be know, when the themes are responsive they are using some framework like bootstrap, foundation, whatever. And then, the slider have to have a css class like "large-12", it should be modified to change its size, for example "large-8", then the slider size will be 8/12.
I hope it help you!

Flexslider2 not resizing on window resize

I have a responsive slider which is supposed to show 1 item per slide at less than 600px width and 3 per slide above that. (as per http://flexslider.woothemes.com/dynamic-carousel-min-max.html) It works if window is loaded at those sizes, but does not work if window is resized (the items per slide don't change). I get an error "Cannot read property 'vars' of undefined" I've tried replacing "$" with jQuery in front of the var but the entire thing breaks at that point.
jQuery(window).load(function() {
// store the slider in a local variable
  var $window = $(window),
flexslider;
// tiny helper function to add breakpoints
function getGridSize() {
return (window.innerWidth < 600) ? 1 :
(window.innerWidth < 900) ? 3 : 3;
}
$(function() {
SyntaxHighlighter.all();
});
jQuery('.flexslider').flexslider({
animation: "slide",
animationLoop: false,
itemWidth: 290,
itemMargin: 0,
 minItems: getGridSize(), // use function to pull in initial value
      maxItems: getGridSize() // use function to pull in initial value
    });
// check grid size on resize event
jQuery(window).resize(function() {
var gridSize = getGridSize();
flexslider.vars.minItems = gridSize;
flexslider.vars.maxItems = gridSize;
});
  });
}(document));

Migrating from jQuery 1.9.1 to 1.10.1 causing error: Object has no method

View my jsFiddle
Resize HTML preview to small width and see that slideshow is resized properly
Change jQuery from 1.9.1 to 1.10.1 (in left pane) and click RUN
Resize HTML preview to a small or large width
Open console, and see error: Object [object Object] has no method 'bjqs'
I cannot figure out what about the bjqs plugin is causing this problem with 1.10.1.
Is there something about the plugin preventing it from working the 2nd time it's called in the resize function?
JavaScript is included here, but jsFiddle linked above is going to be a better place to view it.
Plugin I am using is: http://www.basic-slider.com/
$(function () {
$(window).resize(function () {
if (this.resizeTO) clearTimeout(this.resizeTO);
this.resizeTO = setTimeout(function () {
slideShow(); // re-init on resize stop
}, 500);
});
function slideShow() {
$('.bjqs-controls, .bjqs-markers').remove();
console.log($(window).width());
var ss_width;
var ss_height;
if ($(window).width() >= 600) {
// Desktop
ss_width = 300;
ss_height = 200;
} else if ($(window).width() < 600) {
// Tablet
ss_width = 150;
ss_height = 150;
}
// Load content slideshow
$('#banner-slide').bjqs({
nexttext: 'Next',
prevtext: 'Prev',
showmarkers: true,
centermarkers: true, // horizontally center markers
responsive: false, // enable responsive behaviour
width: ss_width,
height: ss_height
});
}
// Init slide show on load
slideShow();
});
The root cause of the error within said plugin is /^\d\.\d+/i.exec(jQuery.fn.jquery))<1.6 it compares the string "1.10" to "1.6" using alphanumeric sorting, therefore "1.6" > "1.10", so it includes it's own version and doesn't properly prevent conflicts. I'd suggest reporting this as a bug to the plugin author, it should be trivial to fix.

Categories