I'm trying to use left/right arrows to navigate horizontally across my webpage.
Because of Firefox/Chrome handling a default arrow movement differently I had to disable the default movement (Firefox would move it 20px too far right).
<script>
window.addEventListener("keydown", function(e) {
// space and arrow keys
if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
e.preventDefault();
}
}, false);
</script>
I've then got a Keydown function to move 1980px left/right on keypress. (I coudln't get keypress to work because of blocking the default move)
<script>
$(window).keydown(function (e) {
var currentx = 0;
var viewport = 1920;
var btnright = (+currentx) + (+viewport);
var btnleft = (+currentx) - (-viewport);
if ( e.which == 37 ) {
window.scrollTo(btnleft, 0);
currentx = (+currentx) - (-viewport);
} else if ( e.which == 39 ) {
window.scrollTo(btnright, 0);
currentx = (+currentx) + (+viewport);
}
});
</script>
I want it to be recurring (the page is 6000px wide) but I want to move 1 panel (1980px) at a time (Update $Current after each move). Eventually so I can navigate the whole page via arrows.
My issue is I can't get the event to trigger more than once, I can only navigate from 0 to 1980. It won't go any further. Is there a fix for this?
Thanks
As @CBroe stated, your currentx variable is being set to 0 each time that the event is triggered. Try moving the currentx variable declaration out of the event handler like following:
<script>
var currentx = 0,
viewport = 1920;
$(window).keydown(function (e) {
var btnright = (+currentx) + (+viewport),
btnleft = (+currentx) - (-viewport);
if ( e.which == 37 ) {
window.scrollTo(btnleft, 0);
currentx = (+currentx) - (-viewport);
} else if ( e.which == 39 ) {
window.scrollTo(btnright, 0);
currentx = (+currentx) + (+viewport);
}
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With