This is a simple script for horizontal fortune roulette, created using slick slider. Problem: function rollout() executed twice (and all helpers too) because template rendered twice. I'm using iron:router for routing, code:
Router.configure({
loadingTemplate: "loading",
layoutTemplate: "layout"
});
Router.map(function() {
this.route("hello", {
path: "/",
waitOn: function() {
return Meteor.subscribe("games");
}
});
});
hello.js:
Session.setDefault('currentSlide', 0);
Template.hello.events({
'click .create': function(e) {
e.preventDefault();
var ins = {
gameStartTime: new Date(),
finished: false
}
Games.insert({
gameStartTime: new Date(),
finished: "false"
});
Session.set("gameStatus", "waiting");
}
})
Template.hello.helpers({
currentSlide: function() {
var value = Session.get('currentSlide');
if (value === 25) {
return 0;
}
return value;
},
games: function() {
var game = Games.find();
return game;
},
gameHandler: function() {
var game = Games.findOne();
var gameStatus = Session.get("gameStatus");
if (game && game.finished === "false" && gameStatus === "waiting") {
Games.update({_id: game._id}, {
$set: {running: true}
});
} else if (gameStatus === "finished") {
Meteor.call('updateGame', game._id); //remove item from collection after game over; Error here: TypeError: Cannot read property '_id' of undefined;
console.log('game finished');
}
if (game && game.running === true) {
//Set Session variable and launch roulette
Session.set("gameStatus", "running");
rollout(game._id);
}
}
});
var rollout = function(gameid) {
Session.set("gameStatus", "running");
//make div's visible. They are have display:none by default.
document.getElementById("roulette").style.display = "block";
document.getElementById("result").style.display = "block";
document.getElementById("wrapper").style.display = "none";
var speed = 500; //default slider speed
Session.setDefault('speed', speed);
var r = $('#roulette').slick({
centerMode: true,
slidesToShow: 7,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 0,
speed: speed,
draggable: false,
pauseOnHover: false,
cssEase:'linear'
});
var maximum = 14;
var minimum = 0;
var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
var winResult = randomnumber;
var speed = 80;
var currentSlide = Session.get('currentSlide');
function roll(callback) {
Session.set('currentSlide', r.slickCurrentSlide());
if (speed < 800) {
speed += 20;
r.slickSetOption("speed", speed, false);
setTimeout(function() {
roll(callback);
}, 500);
} else if (speed >= 600 && speed < 1300) {
speed += 40;
r.slickSetOption("speed", speed, false);
setTimeout(function() {
roll(callback);
}, 300);
} else if (speed >= 1300 && speed < 20000) {
setTimeout(function() {
speed += 3;
r.slickSetOption('speed', speed, false);
if (Session.get('currentSlide') === winResult) {
r.slickPause();
setTimeout(function() {
//hide roulette div's
document.getElementById("roulette").style.display = "none";
document.getElementById("result").style.display = "none";
document.getElementById("wrapper").style.display = "block";
r.unslick();
Session.set('currentSlide', 0);
Session.set("gameStatus", "finished");
callback(true);
return
}, 10000);
} else {
roll(callback);
}
}, 30)
} else {
callback(true);
}
}
roll(function(callback) {
Meteor.call('updateGame', gameid); //remove item from collection
Session.set("gameStatus", "finished");
});
}
In template i'm using spinner by sacha:spin package and it working fine.
The gameHandler function should not be in your template helpers, which are only meant to supply information to the template. Instead, that logic needs to be moved to an autorun function. This autorun statement will re-run anytime a reactive datasource within it changes.
ex:
Template.hello.onCreated(function() {
this.autorun(function() {
var game = Games.findOne();
var gameStatus = Session.get("gameStatus");
// ...etc
});
}
Related
I am making an app on visual studio 2012. I am navigating from home page to levelOne. On a button click on level one i'm doing some animation,during animation if i get back to home page using windows back button, and then again come back to level one i get the animation running ,i want this animation to get stopped.
This is my first page where the animation will occur:
(function () {
"use strict";
WinJS.UI.Pages.define("/pages/levelOne/levelOne.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function initiazlize(element, options) {
document.getElementById("play").addEventListener("click",function initial(){
roundCount++;
if (flag1 == false) {
//if flag1 is false that means its time for next storyboard
j = 0;
var r3 = Math.random();
if (r3 <= 0.333) {
$(Left).animate({ marginTop: '-=100px' }, 500);
$(Left).animate({ marginTop: '+=100px' }, 500, animateAsync);
//document.getElementById("play").disabled = false;
}
else if (r3 <= 0.666) {
$(midle).animate({ marginTop: '-=100px' }, 500);
$(midle).animate({ marginTop: '+=100px' }, 500, animateAsync);
//document.getElementById("play").disabled = false;
}
else {
$("#bowlThree").animate({ marginTop: '-=100px' }, 500);
$("#bowlThree").animate({ marginTop: '+=100px' }, 500, animateAsync);
//document.getElementById("play").disabled = false;
}
//inside animate Async(), some more animation on capOne,capTwo,capThree and on object, I want to stop animation on these
//There is a counter j, when j reachs 100 animation is stopped
}
});
document.onbeforeunload = function () {
j = 100;
flag1 = true;
$("#capOne").stop(true, false);
$("#capTwo").stop(true, false);
$("#capThree").stop(true, false);
clearTimeout(variableTimer);
window.cancelAnimationFrame(variableTimer);
Debug;
};
},
unload: function () {
// TODO: Respond to navigations away from this page.
$("#capOne").stop();
$("#capOne").css({ "margin-top": "360px", "margin-left": "250px" })
$("#capTwo").css({ "margin-top": "360px", "margin-left": "580px" })
$("#capThree").css({ "margin-top": "360px", "margin-left": "910px" })
////return false;
$("#capOne").fadeOut(100);
WinJS.UI.disableAnimations();
flag1 = true;//if flag1=false then animation is stopped
$("#capOne").stop(true, false);
$("#capTwo").stop(true, false);
$("#capThree").stop(true, false);
clearTimeout(document.variableTimer);
window.cancelAnimationFrame(document.variableTimer);
debugger;
},
updateLayout: function (element, viewState, lastViewState) {
/// <param name="element" domElement="true" />
// TODO: Respond to changes in viewState.
}
});
})();
Here is the navigator.js file
(function () {
"use strict";
var appView = Windows.UI.ViewManagement.ApplicationView;
var nav = WinJS.Navigation;
WinJS.Namespace.define("Application", {
PageControlNavigator: WinJS.Class.define(
// Define the constructor function for the PageControlNavigator.
function PageControlNavigator(element, options) {
this._element = element || document.createElement("div");
this._element.appendChild(this._createPageElement());
this.home = options.home;
this._lastViewstate = appView.value;
nav.onnavigated = this._navigated.bind(this);
window.onresize = this._resized.bind(this);
document.body.onkeyup = this._keyupHandler.bind(this);
document.body.onkeypress = this._keypressHandler.bind(this);
document.body.onmspointerup = this._mspointerupHandler.bind(this);
Application.navigator = this;
}, {
home: "",
/// <field domElement="true" />
_element: null,
_lastNavigationPromise: WinJS.Promise.as(),
_lastViewstate: 0,
// This is the currently loaded Page object.
pageControl: {
get: function () { return this.pageElement && this.pageElement.winControl; }
},
// This is the root element of the current page.
pageElement: {
get: function () { return this._element.firstElementChild; }
},
// Creates a container for a new page to be loaded into.
_createPageElement: function () {
var element = document.createElement("div");
element.style.width = "100%";
element.style.height = "100%";
return element;
},
// Retrieves a list of animation elements for the current page.
// If the page does not define a list, animate the entire page.
_getAnimationElements: function () { //IHDAr
if (this.pageControl && this.pageControl.getAnimationElements) {
return this.pageControl.getAnimationElements();
}
return this.pageElement;
},
// Navigates back whenever the backspace key is pressed and
// not captured by an input field.
_keypressHandler: function (args) {
if (args.key === "Backspace") {
nav.back();
}
},
// Navigates back or forward when alt + left or alt + right
// key combinations are pressed.
_keyupHandler: function (args) {
if ((args.key === "Left" && args.altKey) || (args.key === "BrowserBack")) {
nav.back();
} else if ((args.key === "Right" && args.altKey) || (args.key === "BrowserForward")) {
nav.forward();
}
},
// This function responds to clicks to enable navigation using
// back and forward mouse buttons.
_mspointerupHandler: function (args) {
if (args.button === 3) {
nav.back();
} else if (args.button === 4) {
nav.forward();
}
},
// Responds to navigation by adding new pages to the DOM.
_navigated: function (args) {
var newElement = this._createPageElement();
var parentedComplete;
var parented = new WinJS.Promise(function (c) { parentedComplete = c; });
this._lastNavigationPromise.cancel();
this._lastNavigationPromise = WinJS.Promise.timeout().then(function () {
return WinJS.UI.Pages.render(args.detail.location, newElement,args.detail.state, parented);
}).then(function parentElement(control) {
var oldElement = this.pageElement;
if (oldElement.winControl && oldElement.winControl.unload) {
oldElement.winControl.unload();
}
this._element.appendChild(newElement);
this._element.removeChild(oldElement);
oldElement.innerText = "";
this._updateBackButton();
parentedComplete();
var history = args.detail.state;
WinJS.UI.Animation.enterPage(this._getAnimationElements()).done(
function () {
}
);//IDHAR
}.bind(this));
args.detail.setPromise(this._lastNavigationPromise);//IDHAR BHI
},
// Responds to resize events and call the updateLayout function
// on the currently loaded page.
_resized: function (args) {
if (this.pageControl && this.pageControl.updateLayout) {
this.pageControl.updateLayout.call(this.pageControl, this.pageElement, appView.value, this._lastViewstate);
}
this._lastViewstate = appView.value;
},
// Updates the back button state. Called after navigation has
// completed.
_updateBackButton: function () {
var backButton = this.pageElement.querySelector("header[role=banner] .win-backbutton");
if (backButton) {
backButton.onclick = function () { nav.back(); };
if (nav.canGoBack) {
backButton.removeAttribute("disabled");
} else {
backButton.setAttribute("disabled", "disabled");
}
}
},
}
)
});
})();
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.
I'm a PHP developer and I want to make FlipClock's inital value ease-in. I think it can be done by:
Making clock.incerement()'s interval value flexible, Based on how close is current value, to initial value.
Make a break when the current value was equal to initial value.
I changed this code:
var clock;
var initial = 5000;
$(document).ready(function() {
clock = new FlipClock($('.clock'), 0, {
clockFace: 'Counter',
});
setTimeout(function() {
setInterval(function() {
if(clock.getTime().time >= initial) {
clock.stop();
} else {
clock.increment();
}
}, 100);
});
});
to this one:
var clock;
var initial = 5000;
$(document).ready(function() {
clock = new FlipClock($('.clock'), 0, {
clockFace: 'Counter',
});
setTimeout(function() {
setInterval(function() {
if(clock.getTime().time >= initial) {
clock.stop();
} else {
clock.increment();
}
}, function() {
if ((initial - clock.getTime().time) > 1000) {
return 1;
} else if ((initial - clock.getTime().time) > 100) {
return 10;
} else {
return 1000;
}
});
});
});
But did not worked. What i have to do?!
Thank you.
The interval value is supposed to a time in milliseconds, not a function.
One other way to do it is that you calculate the timeout value is as such
setTimeout(function(){
var x = CalculateCurrentInterval(clock);
setInterval(function() {
if(clock.getTime().time >= initial) {
clock.stop();
} else {
clock.increment();
}
}, x);
})
var CalculateCurrentInverval = function(clock) {
if ((initial - clock.getTime().time) > 1000) {
return 1;
} else if ((initial - clock.getTime().time) > 100) {
return 10;
} else {
return 1000;
}
}
I have not tried it but it should work.
Problem is that you are sending in a function where a number is expected
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.
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