Javascript Viewport Fade In Fade Out - javascript

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.

Related

How to pause a .scrollTop() animation on mouseover? (jsfiddle included)

I am using the following jquery code to create a slow scrolling animation.
http://jsfiddle.net/fhj45f21/
Unfortunately I am having difficulties pausing the animation on mouse over. Could someone please have a look and give me a hint?
function Scroller(y){
this.times = 0;
this.moveInter = 0;
this.backInter = 0;
this.moveBack = function () {
var self = this;
clearInterval(this.moveInter);
this.backInter = setInterval(function () {
self.times -= 5;
y.scrollTop(self.times);
if (self.times == 0) {
return self.startMove();
}
}, 1);
}
this.move = function() {
var self = this;
this.moveInter = setInterval(function () {
self.times++;
y.scrollTop(self.times);
if (self.times == 1200) {
return self.moveBack();
}
}, 50);
}
this.startMove = function() {
this.times = 0;
var self = this;
if (this.backInter != null) {
clearInterval(this.backInter);
}
window.setTimeout(function () {
self.move();
}, 1000);
}
}
jQuery('.textBox').each(function () {
y = jQuery(this);
var scroller = new Scroller(y);
scroller.startMove();
});
Thanks a bunch!
Here you go: http://jsfiddle.net/nxk4vseq/
add an y.hover handler with functions for mousein and mouseout
var scrl=this;
y.hover(function(){
clearInterval(scrl.moveInter);
},function(){
scrl.move();
});

Scroll to top button wont fadeOut

I am having trouble getting my scroll to top button to work. I know its a problem with another animation but I am not able to see what is causing the issue. The problem is when the other animation "starts when scroll hits 500" the scroll to top button will no longer fade out and disappear.
$.chain = function() {
var promise = $.Deferred().resolve().promise();
jQuery.each( arguments, function() {
promise = promise.pipe( this );
});
return promise;
};
function scrollTop(){
if(typeof pageYOffset!= 'undefined'){
return pageYOffset;
}
else{
var b = document.body; //IE 'quirks'
var d = document.documentElement; //IE with doctype
d = (d.clientHeight)? d : b;
return d.scrollTop;
}
}
$(window).on("scroll", function(){
if(scrollTop() >= 600){
$(window).off("scroll");
var animations = $.chain(function() {
return $('#animate1 img').fadeIn('slow').delay(400);
}, function() {
return $('#animate2 img').fadeIn('slow').delay(400);
}, function() {
return $('#animate3 img').fadeIn('slow');
});
};
});
jQuery(document).ready(function() {
var offset = 300;
var duration = 500;
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > offset) {
jQuery('.scroll-top').fadeIn(duration);
} else {
jQuery('.scroll-top').fadeOut(duration);
}
});
});
Thank you for any help.
$(window).off("scroll"); is indeed removing scroll event which you're listening to fadeIn and fadeOut.
Although i havent tried it but an alternative would be to use event namespacing?
something like below:
$.chain = function() {
var promise = $.Deferred().resolve().promise();
jQuery.each( arguments, function() {
promise = promise.pipe( this );
});
return promise;
};
function scrollTop(){
if(typeof pageYOffset!= 'undefined'){
return pageYOffset;
}
else{
var b = document.body; //IE 'quirks'
var d = document.documentElement; //IE with doctype
d = (d.clientHeight)? d : b;
return d.scrollTop;
}
}
$(window).on("scroll.foranimations", function(){ // event name
if(scrollTop() >= 600){
$(window).off("scroll.foranimations"); // event name
var animations = $.chain(function() {
return $('#animate1 img').fadeIn('slow').delay(400);
}, function() {
return $('#animate2 img').fadeIn('slow').delay(400);
}, function() {
return $('#animate3 img').fadeIn('slow');
});
};
});
jQuery(document).ready(function() {
var offset = 300;
var duration = 500;
jQuery(window).on("scroll.forfading", function() { // event name
if (jQuery(this).scrollTop() > offset) {
jQuery('.scroll-top').fadeIn(duration);
} else {
jQuery('.scroll-top').fadeOut(duration);
}
});
});
notice different event names scroll.foranimations and scroll.forfading

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 causing memory leak [closed]

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

Categories