Javascript causing memory leak [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I can't for the life of me figure out why loading this page...
http://polyphonic.hannahkingdev.com/work/cowboys-angels or any other video page sometimes causes the browser to hang and then prompts me to stop the script that is causing the browser to slowdown.
If the video is left to run, by the time you go to close the page, the browser is pretty unresponsive. This is the same in FFox, Safari & Chrome.
Any help finding the memory leak would be most appreciated. I am completely stumped on this one.
Many thanks
var $ = jQuery.noConflict();
$(document).ready(initPage);
// -- Init -- //
function initPage() {
resizeWork();
//hoverWorkImg();
};
// -- Pageload -- //
$(document).ready(function() {
$(".animsition").animsition({
inClass: 'overlay-slide-in-left',
outClass: 'overlay-slide-out-left',
inDuration: 1500,
outDuration: 800,
linkElement: 'a:not([target="_blank"]):not([href^=#]):not([href^=mailto]:not([href^=tel])',
loading: true,
loadingParentElement: 'body', //animsition wrapper element
loadingClass: 'animsition-loading',
loadingInner: '', // e.g '<img src="loading.svg" />'
timeout: false,
timeoutCountdown: 5000,
onLoadEvent: true,
browser: [ 'animation-duration', '-webkit-animation-duration'],
overlay : true,
overlayClass : 'animsition-overlay-slide',
overlayParentElement : 'body',
transition: function(url){ window.location.href = url; }
});
});
// -- Navigation -- //
if (document.getElementById('menu-button') !=null) {
var button = document.getElementById('menu-button');
var menu = document.getElementById('menu-main-navigation');
var menuPos = window.innerHeight;
var menuFixed = false;
button.addEventListener('click', function(ev){
ev.preventDefault();
menu.classList.toggle('navigation--isOpen');
button.classList.toggle('navigation-button--isOpen');
})
updateMenuPosition();
window.addEventListener('resize', updateMenuPosition);
// -- Highlight nav -- /
var $navigationLinks = $('#menu-main-navigation > li > a');
var $sections = $($("section").get().reverse());
var sectionIdTonavigationLink = {};
$sections.each(function() {
var id = $(this).attr('id');
sectionIdTonavigationLink[id] = $('#menu-main-navigation > li > a[href="#' + id + '"]');
});
function throttle(fn, interval) {
var lastCall, timeoutId;
return function () {
var now = new Date().getTime();
if (lastCall && now < (lastCall + interval) ) {
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
lastCall = now;
fn.call();
}, interval - (now - lastCall) );
} else {
lastCall = now;
fn.call();
}
};
}
function highlightNavigation() {
var scrollPosition = $(window).scrollTop();
$sections.each(function() {
var currentSection = $(this);
var sectionTop = currentSection.offset().top;
if (scrollPosition >= sectionTop) {
var id = currentSection.attr('id');
var $navigationLink = sectionIdTonavigationLink[id];
if (!$navigationLink.hasClass('active')) {
$navigationLinks.removeClass('active');
$navigationLink.addClass('active');
}
return false;
}
});
}
$(window).scroll( throttle(highlightNavigation,100) );
}
function updateMenuPosition(){
if(menuFixed){
menu.classList.remove('navigation--white');
menuPos = menu.offsetTop;
menu.classList.add('navigation--white');
} else {
menuPos = menu.offsetTop;
}
updateMenuAttachment();
}
updateMenuAttachment();
window.addEventListener('scroll', updateMenuAttachment);
function updateMenuAttachment(){
var scrollPos = document.documentElement.scrollTop || document.body.scrollTop;
if(!menuFixed && scrollPos >= window.innerHeight - 200){
menu.classList.add('navigation--white');
menuFixed = true;
} else if(menuFixed && scrollPos < window.innerHeight - 200){
menu.classList.remove('navigation--white');
menuFixed = false;
}
}
// -- Smooth scroll to anchor -- /
$('a[href*="#"]')
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (this.hash=="#work") {;
var offsetT = (target.offset().top)-90;
} else {
var offsetT = (target.offset().top);
}
if (target.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: offsetT
}, 1000, function() {
});
}
}
});
// -- Back to top -- /
jQuery(document).ready(function($){
var offset = 300,
offset_opacity = 1200,
scroll_top_duration = 700,
$back_to_top = $('.cd-top');
$(window).scroll(function(){
( $(this).scrollTop() > offset ) ? $back_to_top.addClass('cd-is-visible') : $back_to_top.removeClass('cd-is-visible cd-fade-out');
if( $(this).scrollTop() > offset_opacity ) {
$back_to_top.addClass('cd-fade-out');
}
});
$back_to_top.on('click', function(event){
event.preventDefault();
$('body,html').animate({
scrollTop: 0 ,
}, scroll_top_duration
);
});
});
// -- Animate -- /
new WOW().init();
// -- Inline all SVGs -- /
jQuery('img.svg').each(function(){
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if(typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if(typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Check if the viewport is set, if the viewport is not set the SVG wont't scale.
if(!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {
$svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'))
}
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
});
// -- work grid -- /
function resizeWork() {
var div = $('.work article');
div.css('height', div.width() / 1.9);
}
function hoverWorkImg() {
$('article a').on('mouseenter', function () {
$(this).find('.imagehover:hidden').fadeIn(700);
$(this).find('.second:hidden').fadeIn(700);
$(this).find('.first:visible').fadeOut(700);
})
$('article a').on('mouseleave', function () {
$(this).find('.imagehover:visible').fadeOut(700);
$(this).find('.second:visible').fadeOut(700);
$(this).find('.first:hidden').fadeIn(700);
})
}
// -- Video Page -- /
function playVideoInPage() {
showModal(false);
initPlayer();
startPlay();
}
var $video,
$playPauseButton,
$muteButton,
$seekBar,
isMouseMove=false,
$timing;
function showModal(html) {
if (html !== false) {
$('.work-video').html(html).fadeIn();
}
else {
$('.work-video').fadeIn();
}
hidePlayerControls();
}
function initPlayer() {
$('#video').css('height', $(window).height());
$video = $('.video-container'),
$playPauseButton = $('#play-pause'),
$muteButton = $('#mute'),
$seekBar = $('#seek-bar'),
$timing = $('.timing');
/*setTimeout('showPlayerControls()', 1500);*/
$playPauseButton.on('click', function () {
if ($video.get()[0].paused == true) {
$video.get()[0].play();
$playPauseButton.removeClass('paused');
}
else {
$video.get()[0].pause();
$playPauseButton.addClass('paused');
$timing.stop(true, true);
}
})
$muteButton.on('click', function () {
if ($video.get()[0].muted == false) {
$video.get()[0].muted = true;
$muteButton.addClass('muted');
}
else {
$video.get()[0].muted = false;
$muteButton.removeClass('muted');
}
})
$seekBar.on("click", function (e) {
var x = e.pageX - $(this).offset().left,
widthForOnePercent = $seekBar.width() / 100,
progress = x / widthForOnePercent,
goToTime = progress * ($video.get()[0].duration / 100);
goToPercent(progress)
$video.get()[0].currentTime = goToTime;
});
$video.get()[0].addEventListener("timeupdate", function () {
var value = (100 / $video.get()[0].duration) * $video.get()[0].currentTime;
goToPercent(value)
});
}
function startPlay() {
$playPauseButton.click();
}
function goToPercent(value) {
$timing.css('width', value + '%');
}
function showPlayerControls() {
$('.controls').fadeIn();
isMouseMove=true;
}
function hidePlayerControls() {
$('.controls').fadeOut();
}
function hidePlayerControls() {
setInterval(function() {
if (!isMouseMove) {
hidePlayerControls();
}
isMouseMove=false;
}, 4000);
$(document).mousemove(function (event) {
isMouseMove=true;
showPlayerControls();
});
}

The most likely cause is this code here:
function hidePlayerControls() {
setInterval(function() {
if (!isMouseMove) {
hidePlayerControls();
}
isMouseMove=false;
}, 4000);
so every 4 seconds you start a new interval (interval = repeat until cancelled).
In the first case, you might like to change this to setTimeout
function hidePlayerControls() {
setTimeout(function() {
if (!isMouseMove) {
hidePlayerControls();
}
isMouseMove=false;
}, 4000);
In the second, you could change this to cancel the previous timeout when the mouse moves - this is termed debouncing - though usually with a shorter interval, the principle is the same.
As a general debugging tip, liberally add console.log statements and watch your browser console (there are other ways, this is a basic debugging first-step), eg:
function hidePlayerControls() {
console.log("hidePlayerControls() called");
setInterval(function() {
console.log("hidePlayerControls - interval triggered", isMouseMove);
if (!isMouseMove) {
hidePlayerControls();
}
isMouseMove=false;
}, 4000);
to see just how many times this gets called

Related

Multi-level Accordion Menu: Its possible to open each level with an anchor?

I have a Multi-Level Accordion Menu - from a FAQ - with 2 levels.
Each level have a 13 Questions / Answers.
My problem:
One of the Questions/Answers have a lot of information. (almost 10 pages).
The other Questions/Answers have 3, 4 lines of information each.
The Question with many information is number 7.
Then When I click on question 7 - the answer 7 is open. with many information, and the user must scroll down the page to read all.
Until here, OK. no problem.
but at end - If I click on Question 8 - to read the answer, the menu closes question 7 (ok) - open question 8 (ok) - but the page still in the footer - the page dont scrolls up with the faq..
With all other questions - because they are small - I can see in same screen almost all 13 questions + the answer opened.
With question 7 - no. the page scrolls down and don't scrolls up - when we close the question 7.
There is a way to solve this? I think I need to create an anchor for each question..
Tks a lot!
https://jsfiddle.net/27sdLvmh/
Please, click on Question 7, scrool down to read the answer and then click on question 8. the menu scrolls up - but the screen no.. and the user was lost in the footer of the page.. :D
JS:
;(function ( $, window, document, undefined ) {
var pluginName = 'accordion',
defaults = {
transitionSpeed: 300,
transitionEasing: 'ease',
controlElement: '[data-control]',
contentElement: '[data-content]',
groupElement: '[data-accordion-group]',
singleOpen: true
};
function Accordion(element, options) {
this.element = element;
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Accordion.prototype.init = function () {
var self = this,
opts = self.options;
var $accordion = $(self.element),
$controls = $accordion.find('> ' + opts.controlElement),
$content = $accordion.find('> ' + opts.contentElement);
var accordionParentsQty = $accordion.parents('[data-accordion]').length,
accordionHasParent = accordionParentsQty > 0;
var closedCSS = { 'max-height': 0, 'overflow': 'hidden' };
var CSStransitions = supportsTransitions();
function debounce(func, threshold, execAsap) {
var timeout;
return function debounced() {
var obj = this,
args = arguments;
function delayed() {
if (!execAsap) func.apply(obj, args);
timeout = null;
};
if (timeout) clearTimeout(timeout);
else if (execAsap) func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
function supportsTransitions() {
var b = document.body || document.documentElement,
s = b.style,
p = 'transition';
if (typeof s[p] == 'string') {
return true;
}
var v = ['Moz', 'webkit', 'Webkit', 'Khtml', 'O', 'ms'];
p = 'Transition';
for (var i=0; i<v.length; i++) {
if (typeof s[v[i] + p] == 'string') {
return true;
}
}
return false;
}
function requestAnimFrame(cb) {
if(window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame) {
return requestAnimationFrame(cb) ||
webkitRequestAnimationFrame(cb) ||
mozRequestAnimationFrame(cb);
} else {
return setTimeout(cb, 1000 / 60);
}
}
function toggleTransition($el, remove) {
if(!remove) {
$content.css({
'-webkit-transition': 'max-height ' + opts.transitionSpeed + 'ms ' + opts.transitionEasing,
'transition': 'max-height ' + opts.transitionSpeed + 'ms ' + opts.transitionEasing
});
} else {
$content.css({
'-webkit-transition': '',
'transition': ''
});
}
}
function calculateHeight($el) {
var height = 0;
$el.children().each(function() {
height = height + $(this).outerHeight(true);
});
$el.data('oHeight', height);
}
function updateParentHeight($parentAccordion, $currentAccordion, qty, operation) {
var $content = $parentAccordion.filter('.open').find('> [data-content]'),
$childs = $content.find('[data-accordion].open > [data-content]'),
$matched;
if(!opts.singleOpen) {
$childs = $childs.not($currentAccordion.siblings('[data-accordion].open').find('> [data-content]'));
}
$matched = $content.add($childs);
if($parentAccordion.hasClass('open')) {
$matched.each(function() {
var currentHeight = $(this).data('oHeight');
switch (operation) {
case '+':
$(this).data('oHeight', currentHeight + qty);
break;
case '-':
$(this).data('oHeight', currentHeight - qty);
break;
default:
throw 'updateParentHeight method needs an operation';
}
$(this).css('max-height', $(this).data('oHeight'));
});
}
}
function refreshHeight($accordion) {
if($accordion.hasClass('open')) {
var $content = $accordion.find('> [data-content]'),
$childs = $content.find('[data-accordion].open > [data-content]'),
$matched = $content.add($childs);
calculateHeight($matched);
$matched.css('max-height', $matched.data('oHeight'));
}
}
function closeAccordion($accordion, $content) {
$accordion.trigger('accordion.close');
if(CSStransitions) {
if(accordionHasParent) {
var $parentAccordions = $accordion.parents('[data-accordion]');
updateParentHeight($parentAccordions, $accordion, $content.data('oHeight'), '-');
}
$content.css(closedCSS);
$accordion.removeClass('open');
} else {
$content.css('max-height', $content.data('oHeight'));
$content.animate(closedCSS, opts.transitionSpeed);
$accordion.removeClass('open');
}
}
function openAccordion($accordion, $content) {
$accordion.trigger('accordion.open');
if(CSStransitions) {
toggleTransition($content);
if(accordionHasParent) {
var $parentAccordions = $accordion.parents('[data-accordion]');
updateParentHeight($parentAccordions, $accordion, $content.data('oHeight'), '+');
}
requestAnimFrame(function() {
$content.css('max-height', $content.data('oHeight'));
});
$accordion.addClass('open');
} else {
$content.animate({
'max-height': $content.data('oHeight')
}, opts.transitionSpeed, function() {
$content.css({'max-height': 'none'});
});
$accordion.addClass('open');
}
}
function closeSiblingAccordions($accordion) {
var $accordionGroup = $accordion.closest(opts.groupElement);
var $siblings = $accordion.siblings('[data-accordion]').filter('.open'),
$siblingsChildren = $siblings.find('[data-accordion]').filter('.open');
var $otherAccordions = $siblings.add($siblingsChildren);
$otherAccordions.each(function() {
var $accordion = $(this),
$content = $accordion.find(opts.contentElement);
closeAccordion($accordion, $content);
});
$otherAccordions.removeClass('open');
}
function toggleAccordion() {
var isAccordionGroup = (opts.singleOpen) ? $accordion.parents(opts.groupElement).length > 0 : false;
calculateHeight($content);
if(isAccordionGroup) {
closeSiblingAccordions($accordion);
}
if($accordion.hasClass('open')) {
closeAccordion($accordion, $content);
} else {
openAccordion($accordion, $content);
}
}
function addEventListeners() {
$controls.on('click', toggleAccordion);
$controls.on('accordion.toggle', function() {
if(opts.singleOpen && $controls.length > 1) {
return false;
}
toggleAccordion();
});
$(window).on('resize', debounce(function() {
refreshHeight($accordion);
}));
}
function setup() {
$content.each(function() {
var $curr = $(this);
if($curr.css('max-height') != 0) {
if(!$curr.closest('[data-accordion]').hasClass('open')) {
$curr.css({ 'max-height': 0, 'overflow': 'hidden' });
} else {
toggleTransition($curr);
calculateHeight($curr);
$curr.css('max-height', $curr.data('oHeight'));
}
}
});
if(!$accordion.attr('data-accordion')) {
$accordion.attr('data-accordion', '');
$accordion.find(opts.controlElement).attr('data-control', '');
$accordion.find(opts.contentElement).attr('data-content', '');
}
}
setup();
addEventListeners();
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Accordion( this, options ));
}
});
}
})( jQuery, window, document );
Hey check this demo
changes line 191 -> 194
setTimeout(function()
{
$('html, body').animate({ scrollTop: $content.prev().offset().top }, "fast");
},(1000/60)+200);

How do I find out which js file is responsible for a certain element?

I am testing my page in Chrome. I right click on the element that I am having issues with and I get this:
element.style {
height: 147px;
position: relative;
width: 100%;
overflow: hidden;
}
without a file attached to it. This tells me that the element style is coming from either an inline code (my page has none) or a js file (which my page has a number).
When I turn off the position: relative, I no longer have any issues.
I think I have narrowed it down to one js file that is screwing up my page, but I don't have a clue as to how to fix it or how to figure it out.
Here are some images better describing the issue:
http://i.imgur.com/Yxv2zLe.png
http://i.imgur.com/wtqkqw5.png
If you look at the first image, the blue box over the image needs to be directly over the orange box so that everything lines up properly.
In the second image, when I turn off the position, the image is positions correctly under the overlay.
My problem is that I don't know enough about js to fix the code to fix the position.
Here is the code that I think is responsible, if it helps.
/* ---------------------------------------------------------------------- */
/* Entry Slider
/* ---------------------------------------------------------------------- */
if ($().cycle) {
var entrySliders = $('.entry-slider > ul');
$.fn.cycle.transitions.scrollHorizontal = function ($cont, $slides, opts) {
$cont.css('overflow', 'hidden');
opts.before.push($.fn.cycle.commonReset);
var w = $cont.width();
opts.cssFirst.left = 0;
opts.cssBefore.left = w;
opts.cssBefore.top = 0;
opts.animIn.left = 0;
opts.animOut.left = 0 - w;
if ($cont.data('dir') === 'prev') {
opts.cssBefore.left = -w;
opts.animOut.left = w;
}
};
function initEntrySlider(entrySliders, isFirstTime) {
entrySliders.each(function (i) {
var slider = $(this);
var initPerformed = isFirstTime && slider.data('initInvoked');
if (!initPerformed) {
slider.data('initInvoked', 'true');
var sliderId = 'entry-slider-' + i;
slider.attr('id', sliderId);
var prevButtonId = sliderId + '-prev';
var nextButtonId = sliderId + '-next';
if (slider.data('enable') === 'false') {
return;
}
slider.css('height', slider.children('li:first').height());
var firstSlide = slider.children('li')[0];
var lastSlide = slider.children('li')[slider.children('li').length - 1];
if (slider.children('li').length > 1) {
if (slider.parent().find('#' + prevButtonId).length == 0) {
slider.parent().append('<div class="entry-slider-nav"><a id="' + prevButtonId + '" class="prev">Prev</a><a id="' + nextButtonId + '" class="next">Next</a></div>');
}
}
slider.cycle({
onPrevNextEvent: function (isNext, zeroBasedSlideIndex, slideElement) {
$(slideElement).parent().data('dir', isNext ? 'next' : 'prev');
},
before: function (curr, next, opts, forwardFlag) {
var $this = $(this);
var sliderId = $this.closest('ul').attr('id');
// set the container's height to that of the current slide
$this.parent().stop().animate({height: $this.height()}, opts.speed);
if (opts['nowrap']) {
var prevButton = $('#' + sliderId + '-prev');
var nextButton = $('#' + sliderId + '-next');
if ((firstSlide == next) && (!prevButton.hasClass('disabled'))) {
prevButton.addClass('disabled');
} else {
prevButton.removeClass('disabled');
}
if ((lastSlide == next) && (!nextButton.hasClass('disabled'))) {
nextButton.addClass('disabled');
} else {
nextButton.removeClass('disabled');
}
}
},
containerResize: false,
pauseOnPagerHover: true,
nowrap: false, // if true, the carousel will not be circular
easing: 'easeInOutExpo',
fx: 'scrollHorizontal',
speed: 600,
timeout: 0,
fit: true,
width: '100%',
pause: true,
slideResize: true,
slideExpr: 'li',
prev: '#' + prevButtonId,
next: '#' + nextButtonId
});
}
});
if (Modernizr.touch && $().swipe) {
function doEntrySliderSwipe(e, dir) {
var sliderId = $(e.currentTarget).attr('id');
if (dir == 'left') {
$('#' + sliderId + '-next').trigger('click');
}
if (dir == 'right') {
$('#' + sliderId + '-prev').trigger('click');
}
}
entrySliders.each(function () {
var slider = $(this);
var initPerformed = isFirstTime && slider.data('swipeInvoked');
if (!initPerformed) {
slider.data('swipeInvoked', 'true');
slider.swipe({
click: function (e, target) {
$(target).trigger('click');
},
swipeLeft: doEntrySliderSwipe,
swipeRight: doEntrySliderSwipe,
allowPageScroll: 'auto'
});
}
});
}
}
function initAllEntrySliders(isFirstTime) {
if (isFirstTime) {
var timer = window.setTimeout(function () {
window.clearTimeout(timer);
initEntrySlider($('.entry-slider > ul'), isFirstTime);
}, 100);
} else {
initEntrySlider($('.entry-slider > ul'), isFirstTime);
}
}
function resizeEntrySlider(entrySliders) {
entrySliders.each(function () {
var slider = $(this);
slider.css('height', slider.children('li:first').height());
});
}
function loadEntrySlider() {
var entrySliderImages = $('.entry-slider > ul > li> a > img');
var unloadedImagesCount = 0;
var unloadedImages = [];
entrySliderImages.each(function () {
if (!this.complete && this.complete != undefined) {
unloadedImages.push(this);
unloadedImagesCount++;
}
});
if (unloadedImagesCount == 0) {
initAllEntrySliders(true);
} else {
var initAllEntrySlidersInvoked = false;
var loadedImagesCount = 0;
$(unloadedImages).bind('load', function () {
loadedImagesCount++;
if (loadedImagesCount === unloadedImagesCount) {
if (!initAllEntrySlidersInvoked) {
initAllEntrySlidersInvoked = true;
initAllEntrySliders(true);
}
}
});
var timer = window.setTimeout(function () {
window.clearTimeout(timer);
$(unloadedImages).each(function () {
if (this.complete || this.complete === undefined) {
$(this).trigger('load');
}
});
}, 50);
}
}
loadEntrySlider();
$(window).on('resize', function () {
var timer = window.setTimeout(function () {
window.clearTimeout(timer);
resizeEntrySlider(entrySliders);
}, 30);
});
}
And if I should be asking this somewhere else or something, let me know.

Responsive Layout Issues - ONLY present on iPad. Unsure how to resolve

I'm having a few problems with my portfolio - if/when viewed on an iPad in vertical orientation, scrolling down seems to pull you back to the top. I'm not entirely sure if this is a css/js issue, or something else entirely. Resizing the browser on my computer to the same dimensions doesn't appear to replicate the problem so.. at a bit of a loss.
Has anyone encountered this issue?
Problem site in question:
http://alexandermasters.com/portfolio/weddings/20110827
This is an edited version of the theme template (template was designed strictly to scroll horizontally) but on the pages with the template untouched (http://alexandermasters.com/portfolio/travel/20100928) the issue persists.
Suggestions?
Edit: the offending code (within main.js) is below:
;(function ($, window, $window, $document, isUndefined) {
$(function () {
var $html = $('html'),
$main = $('#main'),
$header = $('#header'),
$footer = $('#footer'),
// Components
$sidebar = $('.sidebar'),
$keyRight = $('#key-right'),
$keyLeft = $('#key-left'),
$navTip = $('.nav-tip'),
$scrollContainer = $('.scroll-container'),
mobileNav,
// Functions
getHorizontalPageHeight,
pageResizer,
// Gloal variables
allowUpscale = $html.is('.upscale');
if (iPadWithIOS4()) {
$html.addClass('ipad-ios4');
}
getHorizontalPageHeight = function () {
return $window.height() - $header.outerHeight() - $footer.outerHeight();
};
/**
* Fixes iOS 7.0~7.0.2 Safari bug. Safari reports $window.height() to be 692, which is not correct.
* Also there's a permanent scrollbar which allows users to scroll 20px, to prevent that we just scroll back to the
* top. This is only required in landscape mode.
*/
if (!!navigator.platform.match(/iPad/) && $html.is('.horizontal-page')) {
var _getHorizontalPageHeight = getHorizontalPageHeight,
IOS7PreventVerticalScroll = function () {
if ($(window).scrollTop() > 0) {
$('body').animate({ scrollTop: 0 }, 200);
}
};
getHorizontalPageHeight = function () {
if ($window.height() == 692) {
return window.innerHeight - $header.outerHeight() - $footer.outerHeight();
}
return _getHorizontalPageHeight();
};
$document.on('scroll', _.debounce(IOS7PreventVerticalScroll, 100));
$window.on('orientationchange.ios7-safari-bug.fluxus', function () {
setTimeout(function () {
if ($window.height() == 692) {
IOS7PreventVerticalScroll();
}
}, 200);
});
}
$('.horizontal-page').each(function () {
var resizer = function () {
var windowWidth = $window.width(),
windowHeight = $window.height(),
// The header is position:fixed we have to calculate the offset for main page dynamically.
headerHeight = $header.outerHeight();
footerHeight = $footer.outerHeight();
// If we are on a small screen
if (windowWidth <= 480) {
if ($html.is('.no-scroll')) {
$main.css({
height: windowHeight - headerHeight,
top: 0
});
} else {
$main.css({
height: 'auto',
top: 0
});
}
} else {
$main.css({
height: getHorizontalPageHeight(),
top: headerHeight
});
}
};
$window.on('resize.horizontal-page.fluxus', _.debounce(resizer));
resizer();
$window.on('orientationchange.horizontal-page.fluxus', function () {
setTimeout(resizer, 10);
});
$main.transition({
opacity: 1
}, 100);
});
/**
* General size adjustments on window resize.
*/
pageResizer = function () {
/**
* Update tinyscrollbar values.
*/
$scrollContainer.each(function () {
var $t = $(this),
tsb = $t.data('tsb');
$t.find('.scrollbar, .track').css('height', $t.height());
tsb && tsb.update();
});
if ($window.width() <= 768) {
// Initialize mobile menu only if we have a small sceen size.
if (!mobileNav) {
// Make mobile menu item array.
var $siteNavigation = $('.site-navigation'),
$mobileNavItems = $siteNavigation.find('a').filter(function () {
var $t = $(this),
level = $t.parents('ul').length;
$t.data('level', level);
if (level == 1) {
return true;
} else {
if ($t.closest('.current-menu-item, .current_page_ancestor').length) {
return true;
}
}
return false;
});
/**
* Initialize mobile menu.
*/
mobileNav = new MobileNav($mobileNavItems, {
openButtonTitle: $siteNavigation.data('menu'),
active: $siteNavigation.find('.current-menu-item > a')
});
}
}
/**
* Trigger vertical center plugin.
*/
setTimeout(function () {
$('.js-vertical-center').verticalCenter();
}, 100);
};
$window.on('resize.page-resizer.fluxus', _.debounce(pageResizer));
pageResizer();
/**
* Arrows and mousewheel navigation plugin.
*/
globalNav = new Navigation({
onSetItems: function () {
this.$items.length && $navTip.show();
}
});
/**
* Full page slider
*/
$('.slider').each(function () {
var $slider = $(this),
slider;
$slider.fluxusSlider({
onNextSlide: function () {
globalNav.options.onNextItem();
},
onPreviousSlide: function () {
globalNav.options.onPreviousItem();
}
});
slider = $slider.data('slider');
slider.slideCount > 1 && $navTip.show();
globalNav.disableKeyboard();
$keyRight.click(function (e) {
slider.next();
e && e.preventDefault();
});
$keyLeft.click(function (e) {
slider.previous();
e && e.preventDefault();
});
});
/**
* Appreciate plugin
*/
var $appreciate = $('.btn-appreciate');
$appreciate.appreciate();
/**
* Sharrre plugin
*/
$('#sharrre-footer').each(function () {
var $el = $(this),
services = {},
buttonsTitle = $el.data('buttons-title');
if (!$el.data('services')) {
return;
}
// retrieve social networks from DOM element.
$.each($el.data('services').split(','), function () {
services[this] = true;
});
$el.sharrre({
share: services,
buttonsTemplate: buttonsTitle ? '<b>' + buttonsTitle + '</b>' : '',
urlCurl: $el.data('curl'),
template: '<b class="share">{title}</b>' +
'<span class="counts">' +
(services.facebook ? '<b class="count-facebook">{facebook}</b>' : '') +
(services.twitter ?'<b class="count-twitter">{twitter}</b>' : '') +
(services.googlePlus ?'<b class="count-plus">{plus}</b>' : '') +
'</span>',
render: function(self, options) {
var html = this.template.replace('{title}', options.title);
html = html.replace('{facebook}', options.count.facebook);
html = html.replace('{twitter}', options.count.twitter);
html = html.replace('{plus}', options.count.googlePlus);
$(self.element).html(html);
$el.show();
}
});
});
$('#sharrre-project').each(function () {
var $el = $(this),
services = {},
buttonsTitle = $el.data('buttons-title');
if (!$el.data('services')) {
return;
}
// retrieve social networks from DOM element.
$.each($el.data('services').split(','), function () {
services[this] = true;
});
$el.sharrre({
share: services,
buttonsTemplate: buttonsTitle ? '<div class="arrow"></div><b>' + buttonsTitle + '</b>' : '',
urlCurl: $el.data('curl'),
template: '<span class="icon"></span><div class="box">' +
'<a class="share" href="#">{title}</a>' +
'<b class="count-total">{total}</b>' +
'</div>',
render: function(self, options) {
var total = options.shorterTotal ? self.shorterTotal(options.total) : options.total,
html = this.template.replace('{title}', options.title).replace('{total}', total);
$(self.element).html(html);
$el.css('display', 'inline-block');
},
afterLoadButtons: function () {
var index = 0,
$buttons = this.$el.find('.button'),
count = $buttons.each( function () {
index++;
$(this).addClass('button-' + index);
}).length;
this.$el.addClass('social-services-' + count);
}
});
});
/**
* Fixes menu issue, when popup is outside the screen.
*/
$('.site-navigation .has-children').hover(function () {
var $submenu = $(this).children('.sub-menu');
if ($submenu.length) {
// if popup is outside the screen, then align it by the right side of the screen.
if ($submenu.offset().left + $submenu.outerWidth() - $(document).scrollLeft() > $window.width()) {
$submenu.addClass('sub-menu-right');
}
}
}, function () {
$(this).children('.sub-menu').removeClass('sub-menu-right');
});
/**
* If our page has a horizontal layout.
*/
if ($html.is('.horizontal-page')) {
/**
* Enable tinyscrollbar plugin.
*/
$scrollContainer.tinyscrollbar({
axis: 'y'
});
/**
* Enable keyboard navigation.
*/
globalNav.options.onNextItem = function () {
$keyRight.addClass('flash');
setTimeout(function () {
$keyRight.removeClass('flash');
}, 200);
};
globalNav.options.onPreviousItem = function () {
$keyLeft.addClass('flash');
setTimeout(function () {
$keyLeft.removeClass('flash');
}, 200);
};
$keyRight.click(function (e) {
globalNav.nextItem();
e && e.preventDefault();
});
$keyLeft.click(function (e) {
globalNav.previousItem();
e && e.preventDefault();
});
}
According to Intheme, the author of the Fluxus Template, the following fix has been released that should solve the issue.
By modifying the following line of code in js/main.js
if (!!navigator.platform.match(/iPad/)) {
to this
if (!!navigator.platform.match(/iPad/) && $html.is('.horizontal-page')) {

Gallery not working on iPad/Mobile Devices

For some reason my gallery isn't working on Mobile devices including iPad, works fine on desktop. Instead of allowing a user to click through, all images appear stacked. The link to my site. The code is
located here
// scroll gallery init
function initCarousel() {
var isTouchDevice = /MSIE 10.*Touch/.test(navigator.userAgent) || ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch;
jQuery('div.view-gallery').scrollGallery({
mask: 'div.frame',
slider: '>ul',
slides: '>li',
btnPrev: 'a.btn-prev',
btnNext: 'a.btn-next',
pagerLinks: '.pagination li',
circularRotation: false,
autoRotation: false,
switchTime: 3000,
animSpeed: 500,
onInit: function(obj){
obj.resizeFlag = true;
obj.win = jQuery(window);
//obj.win.unbind('resize orientationchange load', obj.onWindowResize);
obj.resizeSlides = function(){
obj.slideOffset = obj.slides.eq(0).outerWidth(true) - obj.slides.eq(0).width();
if(!obj.resizeFlag) obj.slides.css({width: ''});
else obj.slides.css({width: obj.mask.width()/2 - obj.slideOffset});
obj.calculateOffsets();
obj.refreshPosition();
obj.refreshState();
}
if(isTouchDevice){
ResponsiveHelper.addRange({
'..767': {
on: function(){
setTimeout(function(){
obj.resizeFlag = true;
obj.resizeSlides();
obj.win.bind('resize orientationchange load', obj.resizeSlides);
}, 100);
}
},
'768..': {
on: function(){
obj.resizeFlag = false;
obj.win.unbind('resize orientationchange load', obj.resizeSlides);
obj.resizeSlides();
}
}
});
}
}
});
jQuery('.scrollable-gallery').scrollableGallery();
}
/*
* scrollableGallery
*/
;(function($) {
function ScrollableGallery(options) {
this.options = {
scrollableArea: '.frame',
listItems: '.list-items',
btnPrev: '.btn-prev',
btnNext: '.btn-next',
animSpeed: 500
}
$.extend(this.options, options);
this.init();
}
ScrollableGallery.prototype = {
init: function() {
this.findElements()
this.setStructure();
this.addEvents();
},
findElements: function() {
this.holder = $(this.options.holder);
this.scrollableArea = this.holder.find(this.options.scrollableArea);
this.listItems = this.scrollableArea.find(this.options.listItems);
this.items = this.listItems.children();
this.lastItem = this.items.last();
this.btnPrev = this.holder.find(this.options.btnPrev);
this.btnNext = this.holder.find(this.options.btnNext);
this.scrollAPI = new jcf.modules.customscroll({
replaces: this.scrollableArea[0]
});
},
setStructure: function() {
var that = this;
if (that.listItems.css('position') === 'static') {
that.listItems.css('position', 'relative');
}
setTimeout(function() {
that.refreshState();
}, 50);
},
refreshState: function() {
this.listItems.css('width', 32700);
this.listItems.css('width', this.lastItem.position().left + this.lastItem.outerWidth(true) + 1);
this.scrollableArea.add(this.scrollableArea.parent()).css({
width: '',
height: ''
});
this.scrollAPI.refreshState();
},
addEvents: function() {
var that = this;
that.btnPrev.bind('click', function(e) {
e.preventDefault();
that.prevSlide();
});
that.btnNext.bind('click', function(e) {
e.preventDefault();
that.nextSlide();
});
win.bind('resize orientationchange load', function() {
that.refreshState();
});
},
nextSlide: function() {
var that = this;
var curPos = this.scrollableArea.scrollLeft();
var pos;
for (var i = 0; i < that.items.length; i++) {
pos = that.items.eq(i).position().left;
if (pos > curPos) {
that.scrollAnimate(curPos, pos);
break;
}
}
},
prevSlide: function() {
var that = this;
var curPos = this.scrollableArea.scrollLeft();
var pos;
for (var i = that.items.length - 1; i >= 0; i--) {
pos = that.items.eq(i).position().left;
if (pos < curPos) {
that.scrollAnimate(curPos, pos);
break;
}
}
},
scrollAnimate: function(from, to) {
var that = this;
var start = new Date().getTime();
setTimeout(function() {
var now = (new Date().getTime()) - start;
var progress = now / that.options.animSpeed;
var result = (to - from) * progress + from;
that.scrollAPI.hScrollBar.scrollTo(result);
if (progress < 1) {
setTimeout(arguments.callee, 10);
} else {
that.scrollAPI.hScrollBar.scrollTo(to);
}
}, 10);
}
}
var win = $(window);
$.fn.scrollableGallery = function(options) {
return this.each(function() {
if (!$(this).data('ScrollableGallery')) {
$(this).data('ScrollableGallery', new ScrollableGallery($.extend({}, {holder: this}, options)));
}
});
}
}(jQuery));
After looking through your code, there were numerous errors with syntax. I have cleaned them up as best as I could, this should help you out.
http://jsfiddle.net/wvWrY/1/
For example, this area was missing a semicolon (no way to call the findElements function, as JS will simply skip to the next line without a semicolon there.)
init: function() {
this.findElements()
this.setStructure();
this.addEvents();
Run your code through a linter, it will greatly improve your syntax structure and ensure little leave out errors like semicolons and commas and brackets aren't omitted.
EDIT: Ok, having looked at your code it appears this is actually due to the !importants in your allmobile.css file. The width and height are set to max-width: 100% (this breaks it because the way the slider works is to extend the gallery as far off screen as possible) and the height to auto (this breaks it because it allows the images to just keep piling on). Once you remove those for the page, it become much much much better and actually works.

Javascript Viewport Fade In Fade Out

I'm trying to accomplish something so simple it's painful, but I've yet to have luck after hours of work.
I have 4 divs, each with the class '.slide'. All I want to do is have them invisible, but fade in when they are in the viewport. If they leave the viewport, they should return to invisible. Any ideas?
$('.slide').waypoint(
function() {
if( $(this).is(":in-viewport") ) {
$(this).animate({
opacity: 1
}, 100);
}
$('.slide').not(this).animate({
opacity: 0
}, 100);
},
{
offset: function() {
return $.waypoints('viewportHeight') - document.getElementById('navigation').clientHeight;
}
}
);
http://jsfiddle.net/Agdax/3/
So i played a little and got this:
/*jslint browser: true */
/*global $ */
(function () {
'use strict';
var invisibleClassName = 'invisible',
scrollWait = 500;
function isInvisible(el) {
var wh = $(window).height(),
wt = $(window).scrollTop(),
eh = $(el).height(),
et = $(el).offset().top;
return ((wh + wt) <= et || wt >= (et + eh));
}
function checkVisibleAll(elements) {
elements.each(function () {
$(this)[(isInvisible(this) ? 'add' : 'remove') + 'Class'](invisibleClassName);
});
}
$.fn.visible = function () {
var elements = this,
scrollTimer = null;
// Don't check too often
function scrolled() {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(function () {
checkVisibleAll(elements);
}, scrollWait);
}
// Onload
checkVisibleAll(elements);
$(window).bind("scroll resize", scrolled);
return this;
};
}());
Animation is visible in modern browsers.

Categories