Scroll effortlessly to the middle, bottom, and top of the page in vue.js using arrow keys for a seamless

I'm interested in implementing a feature that allows users to scroll smoothly up and down the page using the arrow keys.

When the first down key is pressed, I'd like to smoothly scroll to the middle (50%) of the page,
and when the second down key is pressed, I want to scroll to the bottom of the page. The same behavior would apply for the up key.

Can this functionality be achieved with Vue?

Answer №1

Achieving this can be done using pure javascript, making it feasible with vue as well

Take a look at this example

Start by focusing on 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 calculates the view height and current scroll position from the top. Then, it scrolls the page up or down based on the specified amount and relative to the view size.

Note: smooth scrolling may not be supported in all browsers, so consider using smoothscroll-polyfill if you choose to implement this solution.

Next, examine these hooks that handle key events:

  mounted() {
    window.addEventListener("keydown", this.keyHandler);
  },
  beforeUnmount() {
    window.removeEventListener("keydown", this.keyHandler);
  }

And finally, the 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); 
      }
    },

Answer №2

You can achieve this functionality using vue.js and/or JavaScript. If you want to associate these actions with specific html elements, check out KeyCode Modifiers, where you can bind them using v-on. Alternatively, if you prefer using plain JavaScript without integrating it with vue.js, you can implement it like this:

document.onkeydown = keyDownFunc;

function keyDownFunc(e) {
    e = e || window.event;

    if (e.keyCode == '40') {
        // perform desired action
    }
}

In this example, 40 corresponds to the arrow down key. You can easily find key codes by visiting: keycode.info.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Express.js, the value of req.body.data is not defined

Recently, I've been delving into nodejs and express js. My aim is to send a json object to my nodejs application using postman. Below is the code snippet from my app: var express = require("express"); var bodyParser = require('body-parser') ...

Issue with FullCalendar-v4 not displaying all-day events

I am facing an issue with my calendar where recurring events are displaying correctly, but single allDay events are not rendering, and I suspect it may be a field problem. I've attempted to set the event's start time as an iso date, but it doesn ...

What is the reason for utilizing the object name in the object's method rather than using "this"?

Looking at the code snippet above, you can see that store.nextId and store.cache are used in the add method. It makes me wonder why not use this instead? var store = { nextId: 1, cache: {}, add: function(fn) { if (!fn.id) { fn.id = this. ...

Is it possible to use "/path/{?}" in a path when working with Node.js?

I am new to node.js and I'm working on creating a route that will verify the authorization of all users when the specified endpoint begins with /api. I've learned that an optional value can be indicated using ? like {_id?}, but is it possible to ...

What is the best 'event' to pair with an <input/> element in iOS/Android development?

Looking for a way to toggle results when a user starts typing in a search field? Here are some event options: mousedown / mouseup touchstart / touchend focus You could also consider using the "change" event instead of "click" to check for text input an ...

Overlap one element entirely with another

Currently, I am working on a way for an element called overlayElement to completely cover another element known as originalElement. The overlayElement is an iFrame, but that detail may not be significant in this scenario. My goal is to ensure that the over ...

Is there a way to successfully integrate a JavaScript file that has been downloaded from `npm` or `yarn` into a web client or

Currently, I am following a guide titled "Headless Drupal with React" on Medium. The tutorial itself does not address my specific questions. In the tutorial, it demonstrates importing React and ReactDOM directly from CDN in the .html file. My query revolv ...

Encountering Issues with Accessing Property

Upon trying to run my code, the console is displaying an error that I am unable to resolve. The error specifically states: "TypeError: Cannot read property 'author' of undefined." View the StackBlitz project here The error seems to be coming fr ...

Unexpectedly, Internet Explorer 11 is causing the "input" event to fire prematurely

While troubleshooting a JavaScript issue, I came across what seems to be a bug in Internet Explorer 11. I am reaching out here on StackOverflow for validation and to see if anyone else using IE11 can replicate this problem. The problem arises when the val ...

Efficiently sorting items by category name in PHP with Ajax

Currently, I am working on a functionality that involves two dropdown lists. The first one, located at the top, is for selecting a category of meals. Each option in this dropdown has an associated id_cat value. <option value="1">Pâtis ...

Navigating router queries within Nuxt: A step-by-step guide

One of the challenges I am facing is passing value parameters in my URL with the mounted function looking like this: mounted () { this.$router.push({ path: '/activatewithphone', query: { serial: this.$route.params.serial, machin ...

Using PHP to set cookies after making an AJAX request

After reviewing numerous posts on this topic, I am still unable to set any cookies with my code. The initial ajax call in my code looks like this: $("#loginForm").submit(function(event) { event.preventDefault(); var uid = document.getElementById( ...

The issue of fonts module resolution in React-Native remains unsolved

I am embarking on a basic build project using 'create-react-native-app' and yarn as the package manager. My main goal is to incorporate 'native-base' for enhancing the user interface. So far, the only addition to my app.js file is a B ...

The button labeled "modify layout" remains unresponsive when activated

Allow me to start by saying that I am not a coding expert. Currently, I am enrolled in a computer science class and have a basic understanding of HTML, CSS, and some Javascript. However, I have encountered a problem that I cannot solve. When I click on th ...

Is there a reliable method to verify the correctness of an HTML input?

I'm currently developing a quiz using <input type="text"> and <input type="number">. I've noticed that relying on numerous if / else statements in my code is proving to be highly inefficient due to the sheer amoun ...

Comparing AngularJS and Node JS in serving web pages, which is better?

Currently, I'm in the process of learning how to develop a web using angular and node JS. One aspect that I am struggling with is determining where to acquire the URLs for links. After doing some research on stack overflow and various tutorials relate ...

A guide to accessing items imported from a glb file within the Babylon JS game engine

When I use the BABYLON.SceneLoader.ImportMesh() method to load a .glb file created in Blender, one of the objects is named Cube.003. Surprisingly, after calling the method, Cube.003 is not included in the scene.meshes array. It does show up in the scene ...

Troubleshoot the reason behind the malfunctioning Console log on the website

I have been troubleshooting why console.log is not printing anything. I have tried defining and enabling debugger mode, but nothing seems to work. https://i.sstatic.net/5clXf.png Check out the website here: Any suggestions on how I can resolve this issu ...

Vue lightweight loading CSS error: "Undefined property 'denominator'"

Within my project, I have a style.less file that I am loading in the following manner: import "./styles/styles.less"; The contents of the file are structured as shown below. I had to encapsulate the styles to prevent them from affecting the rest of the p ...

Tips for creating a seamless Bootstrap collapse effect

I have noticed a slight flicker in the content collapse when using this code. Is there a way to make it collapse more smoothly? <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script ...