I would like to use the up and down arrow keys to smoothscroll down and up the page.
The first down keypress should take me to the middle (50%),
the second down keypress to the bottom of the page
and vice versa with the up key.
Is this possible with vue?
This should be possible with vue.js and/or some JavaScript. If you want to bind this actions to some html elements, you should take a look at KeyCode Modifiers, where you have the option to bind them on v-on. If you just want to use some JavaScript without binding the actions to vue.js, it could be something like this:
document.onkeydown = keyDownFunc;
function keyDownFunc(e) {
e = e || window.event;
if (e.keyCode == '40') {
// do something
}
}
In this case 40 is arrow down. To get your key codes just visit: keycode.info.
This is possible with pure javascript, hence also possible with vue
Have a look at this example
First, pay attention to this method:
scrollView(amount) {
let scrollFromTop = window.pageYOffset;
const viewHeight = Math.round(window.innerHeight * Math.abs(amount));
if (scrollFromTop % viewHeight === 0) scrollFromTop += Math.sign(amount);
let targetPos;
if (amount > 0)
targetPos = Math.ceil(scrollFromTop / viewHeight) * viewHeight;
else
targetPos = Math.floor(scrollFromTop / viewHeight) * viewHeight;
window.scrollTo({
top: targetPos,
behavior: "smooth"
});
}
It determines view height and current scroll from top. Then, it scrolls the page up or down based on provided amount and in relation with view size.
NB: smooth scrolling is not yet supported in some browsers, you should use smoothscroll-polyfill, if you decide to implement this solution.
Next have a look at these couple of hooks responsible for key event listening:
mounted() {
window.addEventListener("keydown", this.keyHandler);
},
beforeUnmount() {
window.removeEventListener("keydown", this.keyHandler);
}
And last but not least, event handling logic:
keyHandler(e) {
if (e.key === 'ArrowDown') {
e.preventDefault();
this.scrollView(this.scrollAmount);
}
if (e.key === 'ArrowUp') {
e.preventDefault();
this.scrollView(this.scrollAmount * -1);
}
},