.animate() - how to change animation end in progress? - javascript

Goal:
Scroll the window smoothly with PageUp and PageDown keys.
1 press: page scrolls 1 unit.
n quick presses: page scrolls n units.
Let unit = 160px.
I press PageDown. Page starts scrolling to 160px, let's say it's 90px now, while I press PageDown again. It's obvious I don't want to STOP animation here, I want to change it's target frame to point to 320px! So it actually should speed up and NOT STOP until the page is scrolled to 320px.
It seemed obvious to me that all I have to do is changing tween object within step function given to .animate() method as argument.
I wired up second keydown to modify tween.end property, but it didn't work. Animation just stuttered and stopped. The movement always ends at first unit.
The x.stop().animate(...) approach is "no-no". More hickup - unacceptable. There must be a way to change animation end during the process without stopping it, slowing it down or any other unwanted artifacts.
Ok, here's the code:
var isScrolling = false;
var scrollStartPosition = 0;
var scrollTargetPosition = 0;
function goTo(position) {
if (isScrolling) {
scrollTargetPosition = position;
goToUpdate();
}
else {
scrollStartPosition = scrollTargetPosition = position;
position = position >= 0 ? (position <= pageEnd ? position : pageEnd) : 0;
$(page).animate({ scrollLeft : scroll = position }, { start: goToStart, step : goToStep, complete : goToComplete, duration : 500 });
}
}
function goToStart(arg) {
isScrolling = true;
}
function goToUpdate() {
// ???
}
function goToStep(n, tween) {
isScrolling = true;
if (scrollTargetPosition !== scrollStartPosition) {
scrollStartPosition = tween.end = scrollTargetPosition;
}
}
function goToComplete(arg) {
isScrolling = false;
}
Please, help :) I've wasted ca 8h experimenting with this with no luck. jQuery.animate() seems completely ignoring any atempt to change animation in progress, the only thing I succeeded to do is to stop and restart it. I also managed to queue subsequent moves, but the total movement was just FUGLY n jumps instead one normal move.

I've just described how to do it for free ;) It actually works as expected, I missed one very ugly bug in position parameter calculation. It just didn't change with pressing the keys.
Here's fixed goTo() function:
function goTo(position) {
if (isScrolling) {
scroll = scrollTargetPosition = position;
goToUpdate();
}
else {
scrollStartPosition = scrollTargetPosition = position;
position = position >= 0 ? (position <= pageEnd ? position : pageEnd) : 0;
$(page).animate({ scrollLeft : scroll = position }, { start: goToStart, step : goToStep, complete : goToComplete, duration : 500, queue : false });
}
}
The only difference is scroll variable (defined elsewhere) set to the new position after registering the event.
Now it works beautifully.
BTW, if we want use that kind of effect without breaking accessibility - it should be activated with some conditions met first. In my code the screen resoultion is checked. If it's over 1280px wide - I activate special animated view.
So, here's complete solution:
// create a very wide page
// include jQuery and this...
var page;
var pageEnd;
var scroll;
var scrollStep = 160;
var isScrolling = false;
var scrollStartPosition = 0;
var scrollTargetPosition = 0;
function goTo(position) {
if (isScrolling) {
scroll = scrollTargetPosition = position;
}
else {
scrollStartPosition = scrollTargetPosition = position;
position = position >= 0 ? (position <= pageEnd ? position : pageEnd) : 0;
$(page).animate({ scrollLeft : scroll = position }, { start: goToStart, step : goToStep, complete : goToComplete, duration : 500, queue : false });
}
}
function goToStart(arg) {
isScrolling = true;
}
function goToStep(n, tween) {
isScrolling = true;
if (scrollTargetPosition !== scrollStartPosition) {
scrollStartPosition = tween.end = scrollTargetPosition;
}
}
function goToComplete(arg) {
isScrolling = false;
}
function keyDown(e) {
var handled = true;
switch (e.which) {
case 33:
case 38:
goTo(scroll - scrollStep);
break;
case 34:
case 40:
goTo(scroll + scrollStep);
break;
case 35:
goTo(pageEnd);
break;
case 36:
goTo(0);
break;
default:
handled = false;
break;
}
if (handled) e.preventDefault();
}
function init() {
page = $('body');
pageEnd = page[0].scrollWidth - page[0].clientWidth;
page.scrollLeft(1);
if (page.scrollLeft() < 1) page = $('html');
goTo(0);
$('html').css({
'overflow-x' : 'scroll',
'overflow-y' : 'hidden'
});
scroll = page.scrollLeft();
$(window).keydown(keyDown);
}
$(init);

Related

Sidescrolling jittery when changing directions

I made my own sidescrolling parallax using jQuery and the mousewheel plugin. It's working great so far except for the fact that when I change directions of the scroll, it jitters first before actually scrolling (as though it's scrolling one unit to the previous side before actually moving to the correct one). I've tried adding a handler for this which supposedly stops the scroll completely.
Here is my script so far:
var scroll = 0; // Where the page is supposed to be
var curr = scroll; // The current location while scrolling
var isScrolling = false; // Tracker to check if scrolling
var previous = 0; // Tracks which direction it was previously
var loop // setInterval variable
function parallax() {
isScrolling = true;
// Loops until it's where it's supposed to be
loop = setInterval(() => {
if ( curr - scroll == 0 ) {
clearInterval(loop);
isScrolling = false;
return;
}
// Move the individual layers
$('.layer').each(function() {
$(this).css('left', -curr * $(this).data("speed"));
});
// Add/subtract to current to get closer to where it's supposed to be
curr += (scroll < curr) ? -0.5 : 0.5;
}, 25);
}
$(document).ready(() => {
$('.scrolling-container').mousewheel((e, dir) => {
e.preventDefault();
// If the speed's magnitude is greater than 1, revert it back to 1
if ( Math.abs(dir) > 1) {
dir = Math.sign(dir);
}
// If the direction changes, stop the current animation then set scroll to where it currently is
if ( previous !== dir ) {
previous = dir;
isScrolling = false;
scroll = curr;
clearInterval(loop);
}
// If not at the left most scrolling to the left, add to scroll
if ( scroll - dir >= 0 ) scroll -= dir;
// Call parallax function if it's not yet running
if ( !isScrolling ) {
parallax();
}
})
})
I think it's easier to show so here's a codepen of the functional parts: https://codepen.io/ulyzses/pen/yLyoYZm
Try scrolling for a while then change direction, the jittery behaviour should be noticeable.

How to scroll automatically to menu when content swiped

I need to scroll menus automatically when I am swiping the content left or right, for an eg.
when I am swiping to Right and coming to 5th panel slide the navigation should jumped to or scrolled to the 5th menu but now its stays or displays in menu 1 or whatever last menu was clicked only.
My expectation is to create like this eg.
https://js.devexpress.com/Demos/WidgetsGallery/Demo/Pivot/Overview/jQuery/iOS/
I am looking to Achieve two scenario, but I am failing and getting every time an error
If I Make the menu(selected menu) left or center side align then it should always be in left or center side align in initial load of the screen and also when I am swipe the slide content the menu should left or center align, sample eg. above link devexpress
When a content is swiped eg. 5th panel slide then the menu should scroll with respect to it
What I have tried is here and also the Jquery code html for reference
$(document).ready(function(){
$.fn.scrollpane = function(options) {
options = $.extend({
direction: "horizontal",
deadzone: 25,
useTransition: false,
desktop: true,
setupCss: true,
onscroll: function(pos, page, duration) {},
onscrollfinish: function(pos, page) {}
}, options);
var isTouch = "ontouchend" in document || !options.desktop,
onTouchstart = isTouch ? "touchstart" : "mousedown",
onTouchmove = isTouch ? "touchmove" : "mousemove",
onTouchend = isTouch ? "touchend" : "mouseup";
return this.each(function() {
// the scroll pane viewport
var outerElem = $(this);
// a large div containing the scrolling content
var innerElem = $("<div></div>");
innerElem.append(outerElem.children().remove());
outerElem.append(innerElem);
// cache these for later
var outerWidth = outerElem.width();
var outerHeight = outerElem.height();
// boolean
var horizontal = (options.direction === "horizontal");
// the number of pixels the user has to drag and release to trigger a page transition
// natural
var deadzone = Math.max(0, options.deadzone);
// the index of the current page. changed after the user completes each scrolling gesture.
// integer
var currentPage = 0;
// width of a page
// integer
var scrollUnit = horizontal ? outerWidth : outerHeight;
// x coordinate on the transform. -ve numbers go to the right,
// so this goes -ve as currentPage goes +ve
// integer (pixels)
var currentPos = 0;
// min and max scroll position:
// integer (pixels)
var scrollMax = 0;
var scrollMin = -scrollUnit * (innerElem.children().length - 1);
// time to settle after touched:
// natural (ms)
var settleTime = 200;
// dragMid and dragEnd are updated each frame of dragging:
// integer (pixels)
var dragStart = 0; // touch position when dragging starts
var dragMid = 0; // touch position on the last touchmove event
var dragEnd = 0; // touch position on this touchmove event
// +1 if dragging in +ve x direction, -1 if dragging in -ve x direction
// U(-1, +1)
var dragDir = 0;
if (options.setupCss) {
outerElem.css({
position: "relative",
overflow: "hidden"
});
// position the pages:
innerElem.children().each(function(index) {
$(this).css({
position: "absolute",
display: "block",
width: outerWidth,
height: outerHeight
}).css(horizontal ? "left" : "top", scrollUnit * index);
});
}
// natural natural boolean -> void
function scrollTo(position, duration, finish) {
var parameters = {};
parameters[(horizontal ? 'marginLeft' : 'marginTop')] = position;
options.onscroll(position, -position / scrollUnit, duration);
if (options.useTransition) {
innerElem.css({
transition: "none",
transform: horizontal ? ("translate3d(" + position + "px, 0, 0)") : ("translate3d(0, " + position + "px, 0)")
});
}
if (finish) {
if (!options.useTransition) {
innerElem.find('li').animate(parameters, duration);
} else {
innerElem.css({
transition: "all " + (duration === 0 ? "0" : duration + "ms")
});
}
setTimeout(function() {
options.onscrollfinish(position, -position / scrollUnit, duration);
});
} else if (!options.useTransition) {
innerElem.find('li').stop().css(parameters);
}
}
// Immediately set the 3D transform on the scroll pane.
// This causes Safari to create OpenGL resources to manage the animation.
// This sometimes causes a brief flicker, so best to do it at page load
// rather than waiting until the user starts to drag.
scrollTo(0, 0, true);
// bind the touch drag events:
outerElem.on(onTouchstart, function(e) {
e = isTouch ? e.originalEvent.touches[0] || e.originalEvent.changedTouches[0] : e;
dragStart = dragEnd = dragMid = horizontal ? e.pageX : e.pageY;
// bind the touch drag event:
$(this).on(onTouchmove, function(e) {
e = isTouch ? e.originalEvent.touches[0] || e.originalEvent.changedTouches[0] : e;
dragEnd = horizontal ? e.pageX : e.pageY;
dragDir = (dragEnd - dragMid) > 0 ? 1 : -1;
currentPos += dragEnd - dragMid;
dragMid = dragEnd;
scrollTo(currentPos, 0, false);
});
// bind the touch end event
}).on(onTouchend, function(e) {
// boolean
var reset = Math.abs(dragEnd - dragStart) < deadzone;
// real
var scrollPage = -1.0 * currentPos / scrollUnit;
// natural
var nextPage = reset ? currentPage : (dragDir < 0 ? Math.ceil(scrollPage) : Math.floor(scrollPage));
// int
var nextPos = Math.max(scrollMin, Math.min(scrollMax, -scrollUnit * nextPage));
currentPos = nextPos;
currentPage = nextPage;
scrollTo(nextPos, settleTime, true);
outerElem.off(onTouchmove);
});
// set up the menu callback:
outerElem.data("showpage", function(page) {
// int
page = page < 0 ? innerElem.children().length + page : page;
currentPos = Math.max(scrollMin, Math.min(scrollMax, -page * scrollUnit));
currentPage = -currentPos / scrollUnit;
scrollTo(currentPos, settleTime, true);
});
});
};
// Once you've initialized a scrollpane with $().scrollpane(),
// you can use this method to cause it to programmatically scroll
// to a particular page. Useful for creating a navigation menu, or
// those little dots on Apple-store-style product galleries.
//
// Pages are indexed from 0 upwards. Negative numbers can be used
// to index pages from the right.
//
// int -> jQuery
$.fn.showpage = function(index) {
var fn = this.data("showpage");
fn(index);
return this;
};
$(document).bind("touchmove", function() {
return false;
});
$(function() {
//$("#hpane").scrollpane();
$("#hpane").scrollpane({
// onscroll: function(pos, page, duration) {
// $("#pos").text(pos);
// $("#page").text(page);
// $("#snapping").text("no");
// },
onscrollfinish: function(pos, page) {
$("#pos").text(pos);
$("#page").text(page);
$("#snapping").text("yes");
$("ul.pager li").removeClass("active")
$("ul.pager li:nth-child("+(page+1)+")").addClass("active");
}
});
$("ul.pager li").click(function() {
var index = $(this).index();
$("ul.pager li").removeClass("active")
$(this).addClass("active");
$("#hpane").showpage(index);
//$("#vpane").showpage(index);
});
// $("input").click(function() {
// alert(this.value);
// });
});
});

Is it possible to determine where a scroll will end up using javascript? If so, how?

I have a situation where, for example, if a user's scroll will result in a 1000 px change in scrollTop I'd like to know ahead of time.
The perfect example is iCalendar's control over a user's scroll. No matter how hard you scroll in the iCalendar application, the farthest you can scroll is to the next or previous month.
I currently have a very hackish solution to limit scroll behavior, which only takes into account where the user's scroll currently is.
MyConstructor.prototype._stopScroll = function(){
//Cache the previous scroll position and set a flag that will control
//whether or not we stop the scroll
var previous = this._container.scrollTop;
var flag = true;
//Add an event listener that stops the scroll if the flag is set to true
this._container.addEventListener('scroll', function stop(){
if(flag) {
this._container.scrollTop = previous;
}
}.bind(this), false);
//Return a function that has access to the stop function and can remove it
//as an event listener
return function(){
setTimeout(function(){
flag = false;
this._container.removeEventListener('scroll', stop, false);
}.bind(this), 0);
}.bind(this);
};
This approach works, and will stop a scroll in progress, but it is not smooth and I'd love to know if there's a better way to accomplish this.
The key to this question is can I know ahead of time where a scroll will end up. Thanks!!!
Edit: Just found the following project on github:
https://github.com/jquery/jquery-mousewheel
I tried the demo and it's able to report my touchpad and mouse scroll speed. Also it able to stop scrolling without any position fixed hacks :D
I'll have a look in the next few days and see if I can write anything that reports scroll speed, direction, velocity, device etc. Hopefully I'm able to make some jquery plugin that can override all scrolling interaction.
I'll update this post when I've got more info on this subject.
It's impossible to predict where a mouse scroll will end up.
A touchscreen/touchpad swipe on the other hand has a certain speed that will slow down after the user stopped swiping, like a car that got a push and starts slowing down afterwards.
Sadly every browser/os/driver/touchscreen/touchpad/etc has it's own implementation for that slowing down part so we can't predict that.
But we can of course write our own implementation.
We got 3 implementations that could be made:
A. Direction
B. Direction and speed
C. Direction, speed and velocity
iCalender probably uses implementation A.
Implementation A:
Outputs scroll direction to console, user is able to scroll +/- 1px
before the direction is detected.
Demo on JSFiddle
Demo with animation on JSFiddle
(function iDirection() {
var preventLoop = true;
var currentScroll = scrollTop();
function scroll() {
if(preventLoop) {
//Get new scroll position
var newScroll = scrollTop();
//Stop scrolling
preventLoop = false;
freeze(newScroll);
//Check direction
if(newScroll > currentScroll) {
console.log("scrolling down");
//scroll down animation here
} else {
console.log("scrolling up");
//scroll up animation here
}
/*
Time in milliseconds the scrolling is disabled,
in most cases this is equal to the time the animation takes
*/
setTimeout(function() {
//Update scroll position
currentScroll = newScroll;
//Enable scrolling
unfreeze();
/*
Wait 100ms before enabling the direction function again
(to prevent a loop from occuring).
*/
setTimeout(function() {
preventLoop = true;
}, 100);
}, 1000);
}
}
$(window).on("scroll", scroll);
})();
Implementation B:
Outputs scroll direction, distance and average speed to console, user is able to scroll the amount of pixels set in the distance variable.
If the user scrolls fast they might scroll a few more pixels though.
Demo on JSFiddle
(function iDirectionSpeed() {
var distance = 50; //pixels to scroll to determine speed
var preventLoop = true;
var currentScroll = scrollTop();
var currentDate = false;
function scroll() {
if(preventLoop) {
//Set date on scroll
if(!currentDate) {
currentDate = new Date();
}
//Get new scroll position
var newScroll = scrollTop();
var scrolledDistance = Math.abs(currentScroll - newScroll);
//User scrolled `distance` px or scrolled to the top/bottom
if(scrolledDistance >= distance || !newScroll || newScroll == scrollHeight()) {
//Stop scrolling
preventLoop = false;
freeze(newScroll);
//Get new date
var newDate = new Date();
//Calculate time
var time = newDate.getTime() - currentDate.getTime();
//Output speed
console.log("average speed: "+scrolledDistance+"px in "+time+"ms");
/*
To calculate the animation duration in ms:
x: time
y: scrolledDistance
z: distance you're going to animate
animation duration = z / y * x
*/
//Check direction
if(newScroll > currentScroll) {
console.log("scrolling down");
//scroll down animation here
} else {
console.log("scrolling up");
//scroll up animation here
}
/*
Time in milliseconds the scrolling is disabled,
in most cases this is equal to the time the animation takes
*/
setTimeout(function() {
//Update scroll position
currentScroll = newScroll;
//Unset date
currentDate = false;
//Enable scrolling
unfreeze();
/*
Wait 100ms before enabling the direction function again
(to prevent a loop from occuring).
*/
setTimeout(function() {
preventLoop = true;
}, 100);
}, 1000);
}
}
}
$(window).on("scroll", scroll);
})();
Implementation C:
Outputs scroll direction, distance and speeds to console, user is able to scroll the amount of pixels set in the distance variable.
If the user scrolls fast they might scroll a few more pixels though.
Demo on JSFiddle
(function iDirectionSpeedVelocity() {
var distance = 100; //pixels to scroll to determine speed
var preventLoop = true;
var currentScroll = [];
var currentDate = [];
function scroll() {
if(preventLoop) {
//Set date on scroll
currentDate.push(new Date());
//Set scrollTop on scroll
currentScroll.push(scrollTop());
var lastDate = currentDate[currentDate.length - 1];
var lastScroll = currentScroll[currentScroll.length - 1];
//User scrolled `distance` px or scrolled to the top/bottom
if(Math.abs(currentScroll[0] - lastScroll) >= distance || !lastScroll || lastScroll == scrollHeight()) {
//Stop scrolling
preventLoop = false;
freeze(currentScroll[currentScroll.length - 1]);
//Total time
console.log("Time: "+(lastDate.getTime() - currentDate[0].getTime())+"ms");
//Total distance
console.log("Distance: "+Math.abs(lastScroll - currentScroll[0])+"px");
/*
Calculate speeds between every registered scroll
(speed is described in milliseconds per pixel)
*/
var speeds = [];
for(var x = 0; x < currentScroll.length - 1; x++) {
var time = currentDate[x + 1].getTime() - currentDate[x].getTime();
var offset = Math.abs(currentScroll[x - 1] - currentScroll[x]);
if(offset) {
var speed = time / offset;
speeds.push(speed);
}
}
//Output array of registered speeds (milliseconds per pixel)
console.log("speeds (milliseconds per pixel):");
console.log(speeds);
/*
We can use the array of speeds to check if the speed is increasing
or decreasing between the first and last half as example
*/
var half = Math.round(speeds.length / 2);
var equal = half == speeds.length ? 0 : 1;
var firstHalfSpeed = 0;
for(var x = 0; x < half; x++ ) {
firstHalfSpeed += speeds[x];
}
firstHalfSpeed /= half;
var secondHalfSpeed = 0;
for(var x = half - equal; x < speeds.length; x++ ) {
secondHalfSpeed += speeds[x];
}
secondHalfSpeed /= half;
console.log("average first half speed: "+firstHalfSpeed+"ms per px");
console.log("average second half speed: "+secondHalfSpeed+"ms per px");
if(firstHalfSpeed < secondHalfSpeed) {
console.log("conclusion: speed is decreasing");
} else {
console.log("conclusion: speed is increasing");
}
//Check direction
if(lastScroll > currentScroll[0]) {
console.log("scrolling down");
//scroll down animation here
} else {
console.log("scrolling up");
//scroll up animation here
}
/*
Time in milliseconds the scrolling is disabled,
in most cases this is equal to the time the animation takes
*/
setTimeout(function() {
//Unset scroll positions
currentScroll = [];
//Unset dates
currentDate = [];
//Enable scrolling
unfreeze();
/*
Wait 100ms before enabling the direction function again
(to prevent a loop from occuring).
*/
setTimeout(function() {
preventLoop = true;
}, 100);
}, 2000);
}
}
}
$(window).on("scroll", scroll);
})();
Helper functions used in above implementations:
//Source: https://github.com/seahorsepip/jPopup
function freeze(top) {
if(window.innerWidth > document.documentElement.clientWidth) {
$("html").css("overflow-y", "scroll");
}
$("html").css({"width": "100%", "height": "100%", "position": "fixed", "top": -top});
}
function unfreeze() {
$("html").css("position", "static");
$("html, body").scrollTop(-parseInt($("html").css("top")));
$("html").css({"position": "", "width": "", "height": "", "top": "", "overflow-y": ""});
}
function scrollTop() {
return $("html").scrollTop() ? $("html").scrollTop() : $("body").scrollTop();
}
function scrollHeight() {
return $("html")[0].scrollHeight ? $("html")[0].scrollHeight : $("body")[0].scrollHeight;
}
Just had a look at scrollify mentioned in the comments, it's 10kb and needs to hook at every simple event: touch, mouse scroll, keyboard buttons etc.
That doesn't seem very future proof, who know what possible user interaction can cause a scroll in the future?
The onscroll event on the other hand will always be triggered when the page scrolls, so let's just hook the animation code on that without worrying about any input device interaction.
As #seahorsepip states, it is not generally possible to know where a scroll will end up without adding custom behavior with JavaScript. The MDN docs do not list any way to access queued scroll events: https://developer.mozilla.org/en-US/docs/Web/Events/scroll
I found this information helpful:
Normalizing mousewheel speed across browsers
It highlights the difficulty of knowing where the page will go based on user input. My suggestion is to trigger a scroll to Y event when the code predicts the threshold is reached. In your example, if the scroll has moved the page 800 of 1000 pixels in a time window of 250ms, then set the scroll to that 1000 pixel mark and cut off the scroll for 500ms.
https://developer.mozilla.org/en-US/docs/Web/API/window/scrollTo
i'm not pretty sure if i've got what you're looking for. I've had project once, where i had to control the scrolling. Back then i've overwritten the default scroll event, after that you can set a custom distance for "one" scroll. Additionally added jQuery animations to scroll to a specific position.
Here you can take a look: http://c-k.co/zw1/
If that's what you're looking for you can contact me, and i'll see how much i still understand of my own thingy there
is easy to use event listener to do it. Here is a React example:
/**
* scroll promise
*/
const scrollPromiseCallback = useCallback((func:Function) => {
return new Promise((resolve, reject) => {
func(resolve, reject)
})
}, [])
/**
* scroll callback
*/
const scrollCallback = useCallback((scrollContainer, onScrollEnd, resolve) => {
/** 防抖时间 */
const debounceTime = 200
/** 防抖计时器 */
let timer = null
const listener = () => {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
scrollContainer.removeEventListener('scroll', listener)
resolve(true)
onScrollEnd?.()
}, debounceTime)
}
scrollContainer.addEventListener('scroll', listener)
}, [])
const scrollTo = useCallback((props:IUseScrollToProps) => {
return scrollPromiseCallback((resolve, reject) => {
const {
scrollContainer = window, top = 0, left = 0, behavior = 'auto',
} = props
scrollCallback(scrollContainer, props?.onScrollEnd, resolve)
scrollContainer.scrollTo({
top,
left,
behavior,
})
})
}, [scrollCallback, scrollPromiseCallback])

Stop awaiting input after fixed time

I'm new to web programming and I stumbled upon a problem that I couldn't solve and I'm not sure it can be solved. I'm creating a very simple "game" using jquery, and I want to make the thread to stop waiting for the (keydown) input and just carry on with the code, so I can perform either a simple upwards "jump", or a " left jump"/"right jump". Can it be done?
Here follows the codebit from what I've been doing so far:
http://www.codecademy.com/pt/pySlayer10761/codebits/OYQ11a/edit
You need a game loop thats running independantly from your keydown-handler. Elsewise any animation you might hack into the keydown handler might stop the moment no inputs are made anymore.
By looking at your code, I can see you tried to do it by creating a new setTimeout() on those keydowns. You are creating this for every keydown event fired. This is very likely to crash/freeze your browser at some point if the engine does not realize you are creation the same timeout over and over again.
Do it like this: in the onkeydown handler you only set a variable keydowncode to the keycode value. Then you create a new game loop like this
<script>
var keydownCode = 0;
var isInAnimation = false;
var animatedKeydownCode = 0;
var animationStartTime = 0;
var animationStartValue = 0;
// Lightweight keydown handler:
$(document).keydown(function(key) {
keydownCode = parseInt(key.which,10);
}
$(document).keyup(function(key) {
keydownCode = 0;
}
function animation() {
// here comes your animation logic..
// e.g. keep moving for 100 to 200 milliseconds after keypress
// Milli secs difference from
var nowTime = Date.now();
// Animations get prioritized: Only one animation at the same time!
if(isInAnimation) {
switch(animatedKeydownCode) {
case 37:
var delta = (nowTime-animationStartTime)/100*10;
if(delta > 10) { delta = 10; isInAnimation = false; }; // Animation over!
$('img').left(animationStartValue-delta);
case 37:
var delta = (nowTime-animationStartTime)/200*10;
if(delta > 10) { delta = 10; isInAnimation = false; }; // Animation over!
$('img').top(animationStartValue-delta);
case 39:
var delta = (nowTime-animationStartTime)/100*10;
if(delta > 10) { delta = 10; isInAnimation = false; }; // Animation over!
$('img').left(animationStartValue+delta);
}
// Ready to take new input, if its not outdated
} else {
// If some key is down and no animations active
if(keydownCode > 0) {
switch(keydownCode) {
case 37:
animationStartTime = nowTime;
animatedKeydownCode = keydownCode;
animationStartValue = $('img').left();
isInAnimation = true;
case 38:
// Only start a jump if on bottom
if($('img').css("top") == '390px') {
animationStartTime = nowTime;
animatedKeydownCode = keydownCode;
animationStartValue = $('img').top();
isInAnimation = true;
}
case 39:
animationStartTime = nowTime;
animatedKeydownCode = keydownCode;
animationStartValue = $('img').left();
isInAnimation = true;
}
}
}
window.requestAnimationFrame(animation);
}
window.requestAnimationFrame(animation);
</script>
This is no full game, you need to adjust it by yourself to get a working game. E.g. you might want to add some gravity to get mario down again when there is no input..
I think you are looking for setTimeout().
Like this:
setTimeout(function(){
// do something here which will be executed after 5 seconds.
},5000);
You can't stop a thread in javascript as it is single threaded.

javascript 'over-clicking' bug

I have a bug in Javascript where I am animating the margin left property of a parent container to show its child divs in a sort of next/previous fashion. Problem is if clicking 'next' at a high frequency the if statement seems to be ignored (i.e. only works if click, wait for animation, then click again) :
if (marLeft === (-combinedWidth + (regWidth) + "px")) {
//roll margin back to 0
}
An example can be seen on jsFiddle - http://jsfiddle.net/ZQg5V/
Any help would be appreciated.
Try the below code which will basically check if the container is being animated just return from the function.
Working demo
$next.click(function (e) {
e.preventDefault();
if($contain.is(":animated")){
return;
}
var marLeft = $contain.css('margin-left'),
$this = $(this);
if (marLeft === (-combinedWidth + (regWidth) + "px")) {
$contain.animate({
marginLeft: 0
}, function () {
$back.fadeOut('fast');
});
} else {
$back.fadeIn(function () {
$contain.animate({
marginLeft: "-=" + regWidth + "px"
});
});
}
if (marLeft > -combinedWidth) {
$contain.animate({
marginLeft: 0
});
}
});
Sometimes is better if you create a function to take care of the animation, instead of writting animation code on every event handler (next, back). Also, users won't have to wait for the animation to finish in order to go the nth page/box.
Maybe this will help you:
if (jQuery) {
var $next = $(".next"),
$back = $(".back"),
$box = $(".box"),
regWidth = $box.width(),
$contain = $(".wrap")
len = $box.length;
var combinedWidth = regWidth*len;
$contain.width(combinedWidth);
var currentBox = 0; // Keeps track of current box
var goTo = function(n) {
$contain.animate({
marginLeft: -n*regWidth
}, {
queue: false, // We don't want animations to queue
duration: 600
});
if (n == 0) $back.fadeOut('fast');
else $back.fadeIn('fast');
currentBox = n;
};
$next.click(function(e) {
e.preventDefault();
var go = currentBox + 1;
if (go >= len) go = 0; // Index based, instead of margin based...
goTo(go);
});
$back.click(function(e) {
e.preventDefault();
var go = currentBox - 1;
if (go <= 0) go = 0; //In case back is pressed while fading...
goTo(go);
});
}
Here's an updated version of your jsFiddle: http://jsfiddle.net/victmo/ZQg5V/5/
Cheers!
Use a variable to track if the animation is taking place. Pseudocode:
var animating = false;
function myAnimation() {
if (animating) return;
animating = true;
$(this).animate({what:'ever'}, function() {
animating = false;
});
}
Crude, but it should give you the idea.
Edit: Your current code works fine for me as well, even if I jam out on the button. On firefox.

Categories

Resources