I have successfully implemented the scrollTo jQuery plugin which scrolls to the next div with the class “new” when a link is clicked. However, I would also like to be able to use the arrow keys to scroll up and down to the next/previous divs of the same class.
I have looked all over the internet but have been unable to find out how to do this. I am very new to JS so very simple instructions would be appreciated!
Here is the relevant code:
<script type="text/javascript">
jQuery(function($){
$('<div id="next_arrow"></div>')
.prependTo("body") //append the Next arrow div to the bottom of the document
.click(function(){
scrollTop = $(window).scrollTop();
$('.new').each(function(i, h2){ // loop through article headings
h2top = $(h2).offset().top; // get article heading top
if (scrollTop < h2top) { // compare if document is below heading
$.scrollTo(h2, 800); // scroll to in .8 of a second
return false; // exit function
}
});
});
});
</script>
What do I need to add to this to make the arrow keys work?
Thanks,
Ted
You can use the
keydownevent listener to listen for keypresses. You can use this on<input>fields and the like. Because keydown events bubble up the DOM, you can use it on thedocumentobject to catch any keypress on the page:Each keypress has a code. If you use the code above in your web page, you’ll see that the key code for the down arrow is 40. You can solo this out using an
iforswitchstatement in the handler:Now you need to bind in the code that actually jumps to the next heading. I recommend abstracting the code out into a function so you can use it for both keypresses and clicks. Here is the function, together with a variant of your original code that uses it:
Finally, you can add in the keypress code and call the function from there:
Update: To scroll upwards, do two things. Change the
keydownhandler to:and write a
scrollToLast()function based off ofscrollToNew()that finds the last new heading that isn’t on the page: