disable scrolling while scrolling - javascript

I am writting a code , which animates scroll of 100% body.height. Everything works fine , but i am trying to disable the scrolling while the animation last to prevent further unwanted behavior.
i am using this code
function animate(x) {
var start = new Date();
var id = setInterval(function (e) {
var timepassed = new Date() - start;
var progress = timepassed / x.duration;
if (progress > 1) {
progress = 1;
}
var delta = x.delta(progress);
x.step(delta);
if (progress == 1) {
clearInterval(id);
}
}, x.delay);
}
function fak(e) {
e.preventDefault();
return false;
}
function move(e) {
e.preventDefault();
var wheel = e.wheelDelta;
wheel = (wheel == 120) ? "-1" : "1";
var body_height = document.body.offsetHeight;
var scrollIt = body_height * wheel;
var page = window.pageYOffset;
animate({
delay: 10,
duration: 700,
delta: function (p) {
return p;
},
step: function (delta) {
window.scrollTo(0, page + (delta * scrollIt));
}
});
return false;
}
document.body.addEventListener("mousewheel", move, false);
document.body.addEventListener("DOMMouseScroll", move, false);
I tried to assign function fak , on mousewheel , mousescroll in interval and then restoring original assigment to them at the end using
function animate(x) {
var start = new Date();
var id = setInterval(function (e) {
document.body.addEventListener("mousewheel", fak, false);
document.body.addEventListener("DOMMouseScroll", fak, false);
var timepassed = new Date() - start;
var progress = timepassed / x.duration;
if (progress > 1) {
progress = 1;
}
var delta = x.delta(progress);
x.step(delta);
if (progress == 1) {
clearInterval(id);
document.body.addEventListener("mousewheel", move, false);
document.body.addEventListener("DOMMouseScroll", move, false);
}
}, x.delay);
}
But didnt work either. Live demo : http://jsfiddle.net/Trolstover/o2pvo2t8/ Did i overlook something?

i changed a bit on your code.
http://jsfiddle.net/o2pvo2t8/2/
just set a flag "running" while scrolling (at start of animate() ), and clear it at the end.
and execute mov only when no scrolling appears.
hope it helps.
var running;
function animate(x) {
running = 1;
var start = new Date();
var id = setInterval(function (e) {
var timepassed = new Date() - start;
var progress = timepassed / x.duration;
if (progress > 1) {
progress = 1;
}
var delta = x.delta(progress);
x.step(delta);
if (progress == 1) {
clearInterval(id);
running = 0;
}
}, x.delay);
}
function fak(e) {
e.preventDefault();
return false;
}
function move(e) {
e.preventDefault();
if (running==1) return;
var wheel = e.wheelDelta;
console.log(wheel);
wheel = (wheel == 120) ? "-1" : "1";
var body_height = document.body.offsetHeight;
var scrollIt = body_height * wheel;
var page = window.pageYOffset;
animate({
delay: 10,
duration: 700,
delta: function (p) {
return p;
},
step: function (delta) {
window.scrollTo(0, page + (delta * scrollIt));
}
});
return false;
}
document.body.addEventListener("mousewheel", move, false);
document.body.addEventListener("DOMMouseScroll", move, false);

Related

Return after clearInterval

I have a code that runs setInterval in a function. What I try to achive is to exit from that function after clearInterval occured. I set up a condition to check wheter the interval is cleared. I'm struggling to find a method to return from the main Start() function based on the current state of the code.
Code:
function Start() {
var elementX = document.getElementById('moveMeX')
var elementY = document.getElementById('moveMeY')
elementY.style.top = "0px"
var posX = 0
startPosX = 0
var posY = 0
startPosY = 0
var speed = 1
var xIsMoving = true
var yIsMoving = true
var myIntervalX = setInterval(function() {
if(startPosX == 0) {
posX+=speed
elementX.style.left = posX + 'px'
if(posX==100) {
startPosX = 100
}
}
else if (startPosX==100) {
posX-=speed
elementX.style.left = posX + 'px'
if(posX==0) {
startPosX = 0
}
}
}, 10);
function stopX() {
clearInterval(myIntervalX);
xIsMoving = false
}
elementX.addEventListener("mousedown", stopX);
elementX.addEventListener("mousedown", startY);
function startY() {
var myIntervalY = setInterval(function() {
if(startPosY == 0) {
posY+=speed
elementY.style.top = posY + 'px'
if(posY==100) {
startPosY = 100
}
}
else if (startPosY==100) {
posY-=speed
elementY.style.top = posY + 'px'
if(posY==0) {
startPosY = 0
}
}
}, 10);
function stopY() {
elementY.style.zIndex = "-1";
clearInterval(myIntervalY);
yIsMoving = false
}
elementY.addEventListener("mousedown", stopY);
}
if (xIsMoving === false && yIsMoving === false) {
console.log('stopped')
stopped = true
}
}
Start()
Codepen link: https://codepen.io/silentstorm902/pen/podNxVy
The part you state you have a problem with,
if (xIsMoving === false && yIsMoving === false) {
console.log('stopped')
stopped = true
}
currently only runs once: when Start() is first called. At that time, both conditions are false because the variables have their initial declared values of true.
You could create a new setInterval to run this if statement every so often, but it seems unnecessary because your current stopY function is really the place where you know that both xIsMoving and yIsMoving are both false -- because stopY only runs after stopX has run. So just move your statement of stopped=true at the end of the stopY function:
function stopY() {
elementY.style.zIndex = "-1";
clearInterval(myIntervalY);
yIsMoving = false;
console.log("stopped");
stopped = true;
}

Why my javascript dispatchEvent is not working

below is my javascript code. previousPage and NextPage are working properly with HTML button elements.
But I am not sure why addEventListener('wheel') is not working. So I inserted some console.log, then I realize var delta is corret. But, I guess there is a problem 'if (delta ~ ~' area...
const pageList = document.querySelectorAll('.verticalPaging');
const previousPage = document.querySelector('#previousScroller');
const nextPage = document.querySelector('#nextScroller');
const idlePeriod = 100;
const animationDuration = 1000;
let lastAnimation = 0;
let pageIndex = 0;
previousPage.addEventListener('click', ()=> {
if (pageIndex < 1) return;
pageIndex--;
pageList.forEach((section, i) => {
if (i === pageIndex) {
section.scrollIntoView({behavior: "smooth"});
}
});
});
nextPage.addEventListener('click', () => {
if (pageIndex > 4) return;
pageIndex++;
pageList.forEach((section, i) => {
if (i === pageIndex) {
section.scrollIntoView({behavior: "smooth"});
}
})
});
document.addEventListener('wheel', event => {
var delta = event.wheelDelta;
var timeNow = new Date().getTime();
// Cancel scroll if currently animating or within quiet period
if(timeNow - lastAnimation < idlePeriod + animationDuration) {
event.preventDefault();
return;
}
if (delta < 0) {
var event = new Event('click');
nextPage.dispatchEvent(event);
} else {
var event = new Event('click');
previousPage.dispatchEvent(event);
}
lastAnimation = timeNow;
},{passive: false});
The wheel event doesn't have a wheelDelta property, but it has deltaY which I guess you are actually after.
document.addEventListener('wheel', event => {
const timeNow = new Date().getTime();
// Cancel scroll if currently animating or within quiet period
if(timeNow - lastAnimation < idlePeriod + animationDuration) {
event.preventDefault();
return;
}
const clickEvent = new Event('click')
if (event.deltaY < 0) {
nextPage.dispatchEvent(clickEvent);
} else {
previousPage.dispatchEvent(clickEvent);
}
lastAnimation = timeNow;
},{passive: false});
I took the liberty to get rid of var

Combining two Javascript functions to one window.onload not working

I have two functions that I want to run on window.onload event but only the last function seems to work so far. One function is for an image slider and the other one retrieves data from a google spreadsheet cell.
function fun1() { //image slider
var ul;
var li_items;
var imageNumber;
var imageWidth;
var prev, next;
var currentPostion = 0;
var currentImage = 0;
function init() {
ul = document.getElementById('image_slider');
li_items = ul.children;
imageNumber = li_items.length;
imageWidth = li_items[0].children[0].clientWidth;
ul.style.width = parseInt(imageWidth * imageNumber) + 'px';
prev = document.getElementById("prev");
next = document.getElementById("next");
prev.onclick = function() {
onClickPrev();
};
next.onclick = function() {
onClickNext();
};
}
function animate(opts) {
var start = new Date;
var id = setInterval(function() {
var timePassed = new Date - start;
var progress = timePassed / opts.duration;
if (progress > 1) {
progress = 1;
}
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {
clearInterval(id);
opts.callback();
}
}, opts.delay || 17);
}
function slideTo(imageToGo) {
var direction;
var numOfImageToGo = Math.abs(imageToGo - currentImage);
direction = currentImage > imageToGo ? 1 : -1;
currentPostion = -1 * currentImage * imageWidth;
var opts = {
duration: 1000,
delta: function(p) {
return p;
},
step: function(delta) {
ul.style.left = parseInt(currentPostion + direction * delta * imageWidth * numOfImageToGo) + 'px';
},
callback: function() {
currentImage = imageToGo;
}
};
animate(opts);
}
function onClickPrev() {
if (currentImage == 0) {
slideTo(imageNumber - 1);
} else {
slideTo(currentImage - 1);
}
}
function onClickNext() {
if (currentImage == imageNumber - 1) {
slideTo(0);
} else {
slideTo(currentImage + 1);
}
}
}
function fun2() {
// Google spreadsheet js
google.load('visualization', '1', {
callback: function() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1sA7M5kG6Xo8YScD1Df38PIA_G0bvhGRdqoExXg0KJTs/gviz/tq?tqx=out:html&tq?gid=0&headers=0&range=A1:C');
query.send(displayData);
}
});
function displayData(response) {
numRows = response.getDataTable().getValue(0, 0);
document.getElementById('data').innerHTML = numRows;
}
}
var addFunctionOnWindowLoad = function(callback) {
if (window.addEventListener) {
window.addEventListener('load', callback, false);
} else {
window.attachEvent('onload', callback);
}
}
addFunctionOnWindowLoad(fun1);
addFunctionOnWindowLoad(fun2);
This is the answer I've tried link but I can't seem to figure out where I'm going wrong.
This is what I ended up doing, and now all the functions work.
var ul;
var li_items;
var imageNumber;
var imageWidth;
var prev, next;
var currentPostion = 0;
var currentImage = 0;
function init() {
ul = document.getElementById('image_slider');
li_items = ul.children;
imageNumber = li_items.length;
imageWidth = li_items[0].children[0].clientWidth;
ul.style.width = parseInt(imageWidth * imageNumber) + 'px';
prev = document.getElementById("prev");
next = document.getElementById("next");
prev.onclick = function() {
onClickPrev();
};
next.onclick = function() {
onClickNext();
};
}
function animate(opts) {
var start = (new Date());
var id = setInterval(function() {
var timePassed = (new Date()) - start;
var progress = timePassed / opts.duration;
if (progress > 1) {
progress = 1;
}
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {
clearInterval(id);
opts.callback();
}
}, opts.delay || 17);
//return id;
}
function slideTo(imageToGo) {
var direction;
var numOfImageToGo = Math.abs(imageToGo - currentImage);
// slide toward left
direction = currentImage > imageToGo ? 1 : -1;
currentPostion = -1 * currentImage * imageWidth;
var opts = {
duration: 1000,
delta: function(p) {
return p;
},
step: function(delta) {
ul.style.left = parseInt(currentPostion + direction * delta * imageWidth * numOfImageToGo) + 'px';
},
callback: function() {
currentImage = imageToGo;
}
};
animate(opts);
}
function onClickPrev() {
if (currentImage === 0) {
slideTo(imageNumber - 1);
} else {
slideTo(currentImage - 1);
}
}
function onClickNext() {
if (currentImage == imageNumber - 1) {
slideTo(0);
} else {
slideTo(currentImage + 1);
}
}
window.onload = init;
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function fun2() {
// Google spreadsheet js
google.load('visualization', '1', {
callback: function() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1sA7M5kG6Xo8YScD1Df38PIA_G0bvhGRdqoExXg0KJTs/gviz/tq?tqx=out:html&tq?gid=0&headers=0&range=A1:C');
query.send(displayData);
}
});
function displayData(response) {
numRows = response.getDataTable().getValue(0, 0);
document.getElementById('data').innerHTML = numRows;
}
}
addLoadEvent(fun2);
addLoadEvent(function() {
});
I found this function a while ago and believe it or not, I still need to use it every so often. addEventLoad() Just call addEventLoad while passing the function to load.
"The way this works is relatively simple: if window.onload has not already been assigned a function, the function passed to addLoadEvent is simply assigned to window.onload. If window.onload has already been set, a brand new function is created which first calls the original onload handler, then calls the new handler afterwards."
This snippet will load 3 functions on window.onload
Snippet
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function alert1() {
alert("First Function Loaded");
}
function alert2() {
alert("Second Function Loaded");
}
function alert3(str) {
alert("Third Function Loaded; Msg: " + str);
}
addLoadEvent(alert1);
addLoadEvent(alert2);
addLoadEvent(function() {
alert3("This works");
});
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

How to Pause the timer on window blur and resume the timer on window focus event?

Thanks for seeing my question.
I am using wp-pro-quiz plugin for quiz. I want to know that how can I pause the timer if the window is not in focus or is blur and resume it when it is back to focus.?
My code:
I get reset when it get focused
var timelimit = (function () {
var _counter = config.timelimit;
var _intervalId = 0;
var instance = {};
instance.stop = function () {
if (_counter) {
window.clearInterval(_intervalId);
globalElements.timelimit.hide();
}
};
instance.start = function () {
var x;
var beforeTime;
if (!_counter)
return;
var $timeText = globalElements.timelimit.find('span').text(plugin.methode.parseTime(_counter));
var $timeDiv = globalElements.timelimit.find('.wpProQuiz_progress');
globalElements.timelimit.show();
$.winFocus(function (event) {
console.log("Blur\t\t", event);
},
function (event) {
console.log("Focus\t\t", event);
x = _counter * 1000;
beforeTime = +new Date();
});
_intervalId = window.setInterval(function () {
var diff = (+new Date() - beforeTime);
var elapsedTime = x - diff;
if (diff >= 500) {
$timeText.text(plugin.methode.parseTime(Math.ceil(elapsedTime / 1000)));
}
$timeDiv.css('width', (elapsedTime / x * 100) + '%');
if (elapsedTime <= 0) {
instance.stop();
plugin.methode.finishQuiz(true);
}
}, 16);
};
return instance;
})();
Use this wrapper function to pause, resume your timeout.
var Timer;
Timer = function(callback, delay) {
var remaining, start, timerId;
timerId = void 0;
start = void 0;
remaining = delay;
this.pause = function() {
window.clearTimeout(timerId);
remaining -= new Date - start;
};
this.resume = function() {
start = new Date;
window.clearTimeout(timerId);
timerId = window.setTimeout(callback, remaining);
};
this.resume();
};
Intialize it like this, timer = new Timer("callback_function_here", 45000)
In this case total time is 45 seconds for the callback and upon event triggers(blur or focus in your case) it will pause or resume the timer accordingly.
timer.pause() //pause the timer
timer.resume() //resume the timer
P.S - Use this function as per the logic of your code. You will have to make the timer calls accordingly in your code
I did it this way:
var time0 ; var setTimeout_Int; var focused = true; var resume_Fun ;
var addTime =0; var addTimeDiff =0;
window.onfocus = function() {
focused = true;
var d = new Date();
addTimeDiff = addTimeDiff +( d.getTime() - addTime );
resume_Fun();
};
window.onblur = function()
{
focused = false;
};
function init()
{
var d = new Date();
time0 = d.getTime();
setTimeout_Int = setTimeout(update, 1000 )
}
function update()
{
clearTimeout(setTimeout_Int);
var d = new Date();
if(focused)
{
if(d.getTime() -(time0+addTimeDiff) < 20000)
{
setTimeout_Int= setTimeout(update, 1000 )
}
}
else
{
addTime = d.getTime();
resume_Fun = update;
}
}
init();

Javascript replay user input

I'm trying to capture user input (jquery event objects) in a captured array. I am tacking a t property on to the event, which is each event's elapsed time from the start of recording. Then I want to walk back through that array, using a setTimeout within a closure in a for loop in order to trigger those events with the same timing as user input.
I just don't understand why the animations won't play on the way back... !??!
Please, if anyone has insight into this... HELP!
$(function() {
var dancer = document.getElementById('dancer');
var $dancer = $(dancer);
var dancerContainer = document.querySelector('.dancer-container');
var $dancerContainer = $(dancerContainer);
var count = 3;
var captured = [];
var countInterval;
function replayDance(captured) {
for (i = 0; i < captured.length; i++) {
e = captured[i];
t = e.t;
setTimeout((function (e) {
return function () {
// $dancer.trigger(e.type);
// this should be
$dancer.trigger(e.originalEvent);
};
})(e), t);
}
}
function countdown() {
console.log(count);
--count;
if (count == 0) {
console.log('recording')
captureInput();
clearInterval(countInterval);
count = 3;
}
}
function captureInput() {
var mouseCapture = [];
var keyCapture = [];
var start = new Date().getTime();
$(document).on('mousemove.capture', function(event) {
event.t = new Date().getTime() - start;
captured.push(event);
});
$(document).on('keyup.capture', function(event) {
event.t = new Date().getTime() - start;
captured.push(event);
});
setTimeout(function() {
console.log('finished capturing');
$(document).off('.capture');
}, 3000);
}
function followMouse(event) {
var width = $(window).width();
var height = $(window).height();
var mouseX = event.pageX - (width * 0.25);
var mouseY = event.pageY - (height * 0.25);
var angleX = (mouseY / height) * 45;
var angleY = (mouseX / width) * 45;
dancer.style.webkitTransform = "rotateX(" + angleX + "deg) rotateY(" + angleY + "deg)";
console.log(dancer.style.webkitTransform);
}
function resize() {
var y = ($(window).height() - 250) * 0.5;
$("#box").css('margin-top', y + 'px');
}
function triggerAnimation(el, klassName) {
el.stop(true, false).addClass(klassName).one('webkitAnimationEnd', function() { el.removeClass(klassName) });
}
$(document).on('keyup', function(event) {
switch (event.which) {
case 49:
triggerAnimation($dancerContainer, 'shake');
break;
case 50:
triggerAnimation($dancerContainer, 'bounce');
break;
case 51:
triggerAnimation($dancerContainer, 'swing');
break;
case 52:
triggerAnimation($dancerContainer, 'wobble');
break;
}
});
$('#button-record').on('click', function(e) {
countInterval = setInterval(countdown, 1000);
});
$('#button-replay').on('click', function(e) {
if (captured.length) {
replayDance(captured);
} else {
console.log('nothing captured!');
}
})
$(window).on('resize', resize);
$(document).ready(resize);
$(document).on('mousemove', followMouse);
});
I needed to trigger the originalEvent attached to the Event object, rather than trying to trigger the e.type again. Corrected the offending line of code in my post.

Categories

Resources