Jump to specific points in a HTML page using Page up and down

940 views Asked by At

I have a large HTML page consisting of a long list of tables. Each table is about as large as the screen, but varies slightly in size. I'd like to enable the user to use the PgUp and PgDn keys on the keyboard to quickly browse through the tables. Each press of one of these keys shall move one table up or down and place the table's top exactly at the top of the screen.

Is this possible at all?

I considered there might be an HTML element I haven't heard of yet which represents a page break, so that a browser will jump exactly there if one of the Pg** keys is pressed, but I found none.

Is this possible using some Javascript functionality? I considered installing an event listener for key presses and working everything out myself, but that would be rather cumbersome because my page contains a lot of elements which are display:none (i. e. invisible) and they should of course be skipped.

What would be the right approach to achieve this?

1

There are 1 answers

2
Roy Berris On

You should give your tables an ID, like #table1 #table2 #table3. You can now navigate to these tables by pasting their ID behind your URL. Lets implement this with javascript:

var currTable = 1;

document.addEventListener('keydown', function(event) {
 if(event.keyCode == 33) {
     // PageUp was pressed
     if (currTable - 1 > 0) {
       currTable--;
       window.location.hash = "#table" + currTable;
     }
 }
 else if(event.keyCode == 34) {
     // PageDown was pressed
     currTable++;
     window.location.hash = "#table" + currTable;
 }
});

This is the basic example. If you want to, you could implement a check if the table with that specific ID exists

I considered installing an event listener for key presses and working everything out myself, but that would be rather cumbersome because my page contains a lot of elements which are display:none (i. e. invisible) and they should of course be skipped.

Check if the element you're trying to access has a display of none. If it has, check the next element, and continue like this.