Better Javascript Keyboard Navigation

/ Published in: JavaScript
Save to your folder(s)

This fixes the downside of the original javascript keyboard navigation snippet I posted here so that if you manually scroll past to a new chapter mark it will register that and keep track of your location better. The old code would ignore any scrolling you did, so if you read past a chapter and decided to skip one it would just take you to the top of the one you wanted to skip (I don't know if I'm explaining it behavior properly, theres a link in that post you can take to get to the example of the code set up and running on my site to see what I mean) and this one works properly

As with the first JavaScript Navigation snippet you can see it in action on my site and enjoy reading a classic in the process (it's even a different book this time).

As for implementation, the quick and dirty was in applying an onkeydown and an onload to the body tag, for the keycatch and init functions respectively. There are better ways but I was was more interested in testing the code rather than the implementation.

Copy this code and paste it in your HTML
  1. function init(){
  2. currentpos = 0
  3. h1tags = document.body.getElementsByTagName("h3");
  4. setInterval("locator()",500)
  5. }
  6. function locator(){
  7. checkpos=0
  8. while(h1tags[checkpos+1]!=undefined){
  9. if(h1tags[checkpos].offsetTop>(window.pageYOffset-(window.innerHeight)+h1tags[checkpos].clientHeight)){
  10. currentpos = checkpos
  11. checkpos = -3
  12. }
  13. checkpos = checkpos+1;
  14. }
  15. }
  16. function keycatch(){
  17. keypress = event.keyCode
  18. switch(keypress){
  19. case 37: // Left
  20. if(currentpos!=0){
  21. currentpos = currentpos-1;
  22. h1tags[currentpos].scrollIntoView();
  23. }
  24. return false
  25. break;
  26. case 39: // Right
  27. if(h1tags[currentpos+1]!=undefined){
  28. currentpos = currentpos+1;
  29. h1tags[currentpos].scrollIntoView();
  30. }
  31. return false
  32. break;
  33. }
  34. }


Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.