I try to navigate onkeydown with the arrow keys left and right throw my website. With my font awesome links it is working, but I want that it also works onkeydown with the arrow keys on my keyboard.
One problem is, that my site use localization for german an english. That is why my url's look like this:
https://www.example.com/de https://www.example.com/en
https://www.example.com/de/Arbeiten https://www.example.com/en/Projects
Here is my HTML:
<div>
<a href="{{ route('contact') }}" onkeydown="if(e.keyCode == 37) ? window.location.href={{ route('contact') }} : " class="left-arrow arrow-home-left">
<i class="fas fa-angle-left fa-5x"></i>
</a>
</div>
<div>
<a href="{{ route('projects') }}" onkeydown="if(e.keyCode == 39) ? window.location.href={{ route('projects') }} : " class="right-arrow arrow-home-right">
<i class="fas fa-angle-right fa-5x"></i>
</a>
</div>
And my CSS:
body {
background-color: green;
}
.arrow-home-right {
display: inline;
top: 50%;
right: 0;
color: white;
background-color:red;
position: fixed;
}
.arrow-home-left {
display: inline;
top: 50%;
left: 0;
color: white;
background-color:red;
position: fixed;
}
.arrow-home-right:hover, .arrow-home-left:hover {
display: inline;
color: black;
}
Here is my JSFiddle: https://jsfiddle.net/djosxy7z/15/
I want to jump to the next site/page with the arrow keys onkeydown. With the font awesome links it is working, but not wit the keyboard.
Hope, somone can give me a hint. :)
e: Do I have to call the onkeydown function on the body?
You can capture the keydown event with your body tag. Here is an example:
<body onload="onload_handler()">
<div>
<a href="{{ route('contact')}}" class="left-arrow arrow-home-left">
<i class="fas fa-angle-left fa-5x"></i>
</a>
</div>
<p></p>
<div>
<a href="{{ route('projects')}}" class="right-arrow arrow-home-right">
<i class="fas fa-angle-right fa-5x"></i>
</a>
</div>
<script>
function onload_handler() {
document.body.addEventListener("keydown", keydown_handler);
}
function keydown_handler(e) {
let txt = "keydown_handler: keycode = " + e.keyCode;
let anchor = 0;
if(e.keyCode == 37) {
anchor = document.body.querySelector(".left-arrow")
txt = txt + ": left arrow";
} else if(e.keyCode == 39) {
anchor = document.body.querySelector(".right-arrow")
txt = txt + ": right arrow";
}
if(anchor)
txt = txt + ": " + anchor.href;
console.log(txt);
if(anchor)
anchor.click();
}
</script>
</body>
Here is a link to the same site that you posted your fiddle on, using the example above. The example shows which keys you press in the console.