Navigation with arrows by Javascript

On many sites, pages can be navigated using the keyboard by pressing the ← and → keys, while holding the Ctrl key.

What this requires is generally understandable. Somewhere in the code you need to hide the addresses of the previous and next pages and “hang up” the handler at the touch of a key.

Where to write the address? In general, anywhere. We use tags <link>, adding IDs to them:

<link rel="next" href="/portfolio/sokol/2005/" id="NextLink" />
<link rel="prev" href="/portfolio/samsung/megaded/" id="PrevLink" />
<script type="text/javascript" src="/svalka/navigate.js"></script>

This choice at the same time solved another problem – some browsers respond to these tags by displaying additional buttons on the navigation bar.

It remains to hang up the handler for the onkeydown event:

document.onkeydown = NavigateThrough;

And wait until one of the arrows is pressed:

function NavigateThrough (event)
	. . .
	switch (event.keyCode ? event.keyCode : event.which ? event.which : null)
		case 0x25:
			link = document.getElementById ('PrevLink');
		case 0x27:
			link = document.getElementById ('NextLink');
	if (link && link.href) document.location = link.href;	

Opera is an exception. This browser transfers control to the event handler after it executes the default action (the Ctrl + arrow combination in it is already taken). Therefore, in Opera it is necessary to press not only Ctrl, but also Shift – such a three-key combination corresponds to navigation through links from <link> tags.

When you do such things, it is important to correctly figure out which page to consider the previous one, and which next.


December, 14 2018 at 10:55

I create web projects, develop, optimize and promote websites. If you have any ideas or want to suggest something, then write to me and my team.

Top ↑

Leave a Reply