Sunday, July 9, 2023

Javascript buttons to jump to next anchor

<head>
<!-- Hide script-dependent content -->
<style type="text/css">
.requiresScript-block, .requiresScript-inLine {
  display: none;
}
div.spacer {
  height: 500px;
  border: 1px solid blue;
}
</style>
<script type="text/javascript">

function goToNextAnchor() {
  var anchors = document.anchors;
  var loc = window.location.href.replace(/#.*/,'');
  var nextAnchorName;

  // Get name of the current anchor from the hash
  // if there is one
  var anchorName = window.location.hash.replace(/#/,'');

  // If there is an anchor name...
  if (anchorName) {

    // Find current element in anchor list, then
    // get next anchor name, or if at last anchor, set to first
    for (var i=0, iLen=anchors.length; i<iLen; i++) {
      if (anchors[i].name == anchorName) {
        nextAnchorName = anchors[++i % iLen].name;
        break;
      }
    }
  }

  // If there was no anchorName or no match, set nextAnchorName to first anchor name
  if (!nextAnchorName) {
    nextAnchorName = anchors[0].name;
  }

  // Go to new URL
  window.location.href = loc + '#' + nextAnchorName;
}

// Display script-dependent content if javascript available
document.write(
  '\u003Cstyle type="text/css"\u003e' +
  '.requiresScript-block {display: block;}' +
  '.requiresScript-inLine {display: inline;}' +
  '\u003C/style\u003e'
);
</script>
</head>
<body>
  <ol>
    <li><a href="#header">Go to header</a>
    <li><a href="#box1">Go to box 1</a>
    <li><a href="#box2">Go to box 2</a>
    <li><a href="#box3">Go to box 3</a>
    <li><a href="#box4">Go to box 4</a>
    <li><a href="#box5">Go to box 5</a>
  </ol>

  <!-- Only shown if javascript available -->

  <a name="header"></a><h1>Header
  <button class="requiresScript-inLine" onclick="goToNextAnchor()">Next</button></h1>
  <div class="spacer">content</div>
  <a name="box1"></a>Box 1
    <button class="requiresScript-inLine" onclick="goToNextAnchor()">Next</button>
  <div class="spacer">content</div>
  <a name="box2"></a>Box 2
    <button class="requiresScript-inLine" onclick="goToNextAnchor()">Next</button>
  <div class="spacer">content</div>
  <a name="box3"></a>Box 3
    <button class="requiresScript-inLine" onclick="goToNextAnchor()">Next</button>
  <div class="spacer">content</div>
  <a name="box4"></a>Box 4
  <button class="requiresScript-inLine" onclick="goToNextAnchor()">Next</button>
  <div class="spacer">content</div>
  <a name="box5"></a>Box 5
  <button class="requiresScript-inLine" onclick="goToNextAnchor()">Next</button>
</body>