Introduction
We have some HTML tables that are many pages long divided into a dozen or more sections. We (Ok, I!) needed a way to skip sections without having to scroll or page down. CodeProject allows you to jump from one message thread to the next by using Ctrl + Left/Right/Up/Down Arrow keys. Looking at CP's code (imitation is the sincerest form of laziness), it seemed much more complicated than what I needed, so I decided to write my own.
Using the Code
The code can be summarized as follows:
- Count the total number of sections in
onload
. - Capture when Ctrl key is pressed in
onkeydown
. - Scroll to appropriate section when arrows are pressed with Ctrl key in
onkeydown
, while staying within the outer limits of the section count. - Release Ctrl key when no longer needed in
onkeyup
.
To use the code, add the following JavaScript block inside the HTML's HEAD
element.
<script type="text/javascript" language="javascript">
var index = -1;
var ctrlSelected = false;
var sectionCount = 0;
function getSectionsCount()
{
sectionCount = document.getElementsByName("section").length;
};
function moveToNextSection()
{
var curr = document.getElementsByName("section")[index];
curr.scrollIntoView(true);
};
document.onkeydown = function()
{
var e;
if (window.event)
e = event.keyCode;
else if (event.which)
e = event.which;
if (e == 17)
{
ctrlSelected = true;
}
else if (e == 35)
{
index = sectionCount;
}
else if (e == 36)
{
index = -1;
}
if (ctrlSelected)
{
if (e == 38)
{
if (index > 0)
{
index = index - 1;
moveToNextSection();
}
return false;
}
else if (e == 40)
{
if (index < sectionCount - 1)
{
index = index + 1;
moveToNextSection();
}
return false;
}
}
return true;
};
document.onkeyup = function()
{
var e;
if (window.event)
e = event.keyCode;
else if (event.which)
e = event.which;
if (e == 17)
{
ctrlSelected = false;
}
};
</script>
For each TD
or TR
section, I use id="section"
as my section ID.
In the BODY
element, add the attribute onload="getSectionsCount()"
to count the number of sections once the HTML page is loaded.
Limitations
If you page or scroll away from the section you're at and use this shortcut to skip sections, it continues from where you were last at. I did look into extending it so that it moves up or down from what is actually displayed on the screen, but that would have bloated the code considerably since each browser has its own set of functions and issues.
History
- Version 1.0 - July 23, 2013 - Initial release