0

I am having a difficult time trying to find my answer on my own, so maybe someone can help.

I have a horizontal scrolling div (wrapper) with mutliple divs (box) inside of it.

I want to be able to click the keyboard arrows keys to jump to the next element. The window would be scrolling left with each jump.

I've created a basic jsFiddle that people can add too to add keyboard navigation.

http://jsfiddle.net/ryanjay/JjhUN/

2 Answers 2

1

This can be accomplished by storing the positions of the boxes and then testing that against the window.scrollX position. You then animate to the closest box depending on the arrow key pressed.

var boxLefts = []; $('.box').each(function(i, el){ boxLefts.push(this.offsetLeft); }); $(document).keydown(function(e) { var dir = false, targetLeft = -1; switch (e.keyCode) { case 37: dir = -1; break; case 39: dir = 1; break; } if (dir) { e.preventDefault(); winLeft = window.scrollX; $.each(boxLefts, function(i, v){ if ((dir == 1 && winLeft < v && targetLeft < 0) || (dir == -1 && winLeft > v)) { targetLeft = v; } }); if (targetLeft >= 0) { $('html, body').animate({scrollLeft: targetLeft}, 1000); } } }); 

See Demo

Sign up to request clarification or add additional context in comments.

1 Comment

So... I've gotten this to work on my index.html page. Works perfectly. But I am running into a problem that I can't figure out. I am dynamically loading in a new gallery of photos (.box) into a wrapper. When I do this, and use my arrows for navigation, it jumps to the last image on the next, and back to the first on the prev, skipping EVERYTHING in between. I tried to just turn it into a function, then call that function on window.load, as well as after loading in the new .html page. Problem is still there. Got any ideas?
1

yuuuuuuuuuppppppppppppyyyyyyyyyyyyy got it done finaly.. :)

check it here : http://jsfiddle.net/JjhUN/7/

$(function() { var index = 0; var elems = $('.box'); var len = $('.box').length; elems.eq(index).addClass('selected_div'); $(document).keyup(function(e) { var key = e.keyCode || e.charCode || e.which; switch (key) { case 39: if(index < len-1){ elems.eq(index).removeClass('selected_div'); index = index +1; elems.eq(index).addClass('selected_div'); $('#wrapper').animate({"left": "-=210px"}, "slow"); } break; case 37: if(index > 0){ elems.eq(index).removeClass('selected_div'); index = index - 1; elems.eq(index).addClass('selected_div'); $('#wrapper').animate({"left": "+=210px"}, "slow"); } break; } }); }); 

CSS:

#wrapper { position:absolute; white-space: nowrap; } .selected_div{ background-color: blue; } .box { width: 200px; height: 200px; border: 1px solid red; margin: 0 10px 0 0; display: inline-block; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.