Jump To Section Of Webpage With A Keystroke - HTML

You can make it so you can automatically scroll to different areas of your website by hitting a key. For example, if you have a lengthy book all on one page, you can let your reader skip to the next or previous chapter with one type the up or down arrow.

Put this code inside the <head></head> of your html:

<script type"text/javascript">
function detectKey(e) {
 var currentImg = 0;
   if (!e) { e = window.event; } // sanity
   switch (e.keyCode) {
    case 38: { // up
     if (currentImg > 1) {
   case 40: { // down
    if (currentImg <= 3) {
   default: {
  return false;
 function scrollImg(dir) {
  if (dir == "up") {
  else if (dir == "down") {
  var img = document.getElementById("img" + currentImg);
 document.onkeyup = function(event) { detectKey(event); };
 window.onload = function() { scrollImg("down"); };

This establishes which section of the website that it will scroll to when it is first opened (0 indicates before 1st section).

This is the key stroke that will jump you to the previous section. 38 is the up arrow (See all key codes)

This is the key stroke that will jump you to the next section. 40 is for the down arrow (See all key codes)

This is the maximum number of sections that you can jump to.

Now put this code within the <body></body>:

  <div id="sc" class="imgs">
 <div id="img1" class="img">
   (Content of 1st section)

 <div id="img2" class="img">
   (Content of 2nd section)

 <div id="img3" class="img">
   (Content of 3rd section)


Add as many divs as you need. Or you can achieve the same thing with <a href="" id="img1"></a>. But you might as well use divs. Now when you open the website, it will always scroll to the beginning of img1. Then as you type the key arrow up or down it will skip up or down to the next img.

But now the page will scroll to img1 when you first open the page, even if you have clicked on a link to somewhere within the page. How do you allow another webpage to link to somewhere within your page without it automatically scrolling to the top?

Inside the <head></head> of your html, replace the var currentImg = 0; with:

 if (window.location.hash == '#img1') {
  var currentImg = 0;}
 else if (window.location.hash == '#img2') {
  var currentImg = 1;}
 else if (window.location.hash == '#img3') {
  var currentImg = 2;}
    }else{var currentImg = 0;}

This lets the browser know that if the address bar searches for a certain hash anchor, then that hash anchor should be the section of website to scroll to first. If a hash anchor is in the address bar that you didn't specify for, it will just default to 0, before the 1st img.

1 comment:

Bryan Harnois said...
This comment has been removed by a blog administrator.

Post a Comment

Comments or names that include links or names of external websites will be marked spam.