Reputation: 598
As you can see with this fiddle, I'm trying to allow the user to use the left and right arrow keys to move to different sections (each of them are the size of the window) in the page.
Here is a sample of the Javascript I use:
var windowHeight = $(window).height(), windowWidth = $(window).width();
$(".slide").css("height", windowHeight);
$(".slide").css("width", windowWidth);
$(window).resize(function () {
"use strict";
var windowHeight = $(window).height(), windowWidth = $(window).width(), centerHeight = windowHeight / 2, centerWidth = windowWidth / 2;
$(".slide").css("height", windowHeight);
$(".slide").css("width", windowWidth);
});
function leftArrowPressed() {
"use strict";
var windowHeight = Math.abs($(window).height()) * -1;
$("html, body").animate({ scrollTop: "+=" + windowHeight});
}
function rightArrowPressed() {
"use strict";
var windowHeight = $(window).height();
$("html, body").animate({ scrollTop: "+=" + windowHeight });
}
document.onkeydown = function (evt) {
"use strict";
evt = evt || window.event;
switch (evt.keyCode) {
case 37:
leftArrowPressed();
break;
case 39:
rightArrowPressed();
break;
}
};
This works for the most part; when the user presses the left/right arrow keys, it goes up/down for the window.height. The problem with this is that when the user scrolls through the page for a bit, it goes out of line when the user goes back to pressing the arrow keys.
What is the least complicated to fix this? I would accept using the href
and id
attributes, as well as jQuery, or even simple rounding, to make sure it goes back to default. Thanks in advance!
Upvotes: 0
Views: 839
Reputation: 5115
Instead of using the window's height, try instead using that section's offset. If you have a certain element, it's offset represents the amount of space from the top. Use that instead of +=.
Here's an updated fiddle: http://jsfiddle.net/VuVW6/1/
Basically, using this method, you will always go to the top of each section.
Here's the updated portion of your JS. Everything else can stay the same:
var current = 0;
var sections = $(".slide")
function leftArrowPressed() {
"use strict";
current -= 1;
current = Math.min(sections.length-1, Math.max(current, 0));
$("html, body").animate({ scrollTop: sections.eq(current).offset().top});
}
function rightArrowPressed() {
"use strict";
current += 1;
current = Math.min(sections.length-1, Math.max(current, 0));
$("html, body").animate({ scrollTop: sections.eq(current).offset().top});
}
Notice how using offset()
makes it so that the correct value is always given to scroll top. (No more relying on the math to work out)
Also, just a tip: call finish() before your next animate call so that the animation queue is cleared. Don't want any infinite loops. :)
Upvotes: 2