Navigate through dropdown options using arrow keys - vuejs

I am currently working on creating an autocomplete feature using Vue.js.

However, I have run into an issue with the scroll animation.

The goal is to enable scrolling by clicking on the arrow keys in the direction of the key pressed, but the scroll should only happen when the option is not visible.

I would like something similar to this functionality, but implemented in Vue.js / JavaScript - http://jsfiddle.net/kMzR9/3/

.

If you are unable to identify the problem in the example provided here due to the small screen size, you can check out the jsfiddle link for a closer look - https://jsfiddle.net/v7yd94r5/

.

Here is an overview of my implementation:

// Your code goes here...
#app {
    // Styling for the app container
}

.autocomplete {
    // Styles for the autocomplete component
}

.autocomplete-results {
    // Styles for the autocomplete results dropdown
}

.autocomplete-result {
    // Styles for each individual result item
}
<script src="[Vue.js CDN URL]"></script>
<div id="app">
  <autocomplete :items="[ 'Apple', 'Banana', 'Orange', 'Mango', 'Pear']" />

</div>

Answer №1

To ensure the proper functionality, a function is required to verify the position of the current element and adjust the scroll container if necessary. Additionally, there seems to be an issue with the arrowDown function as indicated below:

<ul ... ref="scrollContainer" ... >
    ...
    <li ref="options" ... >
    ...
</ul>

onArrowDown(ev) {
    ev.preventDefault()
    if (this.arrowCounter < this.results.length-1) { <--- Adjustment needed here -1
        this.arrowCounter = this.arrowCounter + 1;
        this.fixScrolling();
    }
},
onArrowUp(ev) {
    ev.preventDefault()
    if (this.arrowCounter > 0) {
        this.arrowCounter = this.arrowCounter - 1;
        this.fixScrolling()
    }
},
fixScrolling(){
    const liH = this.$refs.options[this.arrowCounter].clientHeight;
    this.$refs.scrollContainer.scrollTop = liH * this.arrowCounter;
},

const Autocomplete = {
  name: "autocomplete",
  template: "#autocomplete",
  props: {
    items: {
      type: Array,
      required: false,
      default: () => Array(150).fill().map((_, i) => `Fruit ${i+1}`)
    },
    isAsync: {
      type: Boolean,
      required: false,
      default: false
    }
  },

  data() {
    return {
      isOpen: false,
      results: [],
      search: "",
      isLoading: false,
      arrowCounter: 0
    };
  },

  methods: {
    onChange() {
      // Alert the parent about the change
      this.$emit("input", this.search);

      // Is asynchronous data being provided?
      if (this.isAsync) {
        this.isLoading = true;
      } else {
        // Search through the array
        this.filterResults();
        this.isOpen = true;
      }
    },

    filterResults() {
      // Convert all strings to lowercase
      this.results = this.items.filter(item => {
        return item.toLowerCase().indexOf(this.search.toLowerCase()) > -1;
      });
    },
    setResult(result, i) {
      this.arrowCounter = i;
      this.search = result;
      this.isOpen = false;
    },
    onArrowDown(ev) {
      ev.preventDefault()
      if (this.arrowCounter < this.results.length-1) {
        this.arrowCounter = this.arrowCounter + 1;
        this.fixScrolling();
      }
    },
    onArrowUp(ev) {
      ev.preventDefault()
      if (this.arrowCounter > 0) {
        this.arrowCounter = this.arrowCounter - 1;
        this.fixScrolling()
      }
    },
    fixScrolling(){
      const liH = this.$refs.options[this.arrowCounter].clientHeight;
      this.$refs.scrollContainer.scrollTop = liH * this.arrowCounter;
    },
    onEnter() {
      this.search = this.results[this.arrowCounter];
      this.isOpen = false;
      this.arrowCounter = -1;
    },
    showAll() {
      this.isOpen = !this.isOpen;
(this.isOpen) ? this.results = this.items : this.results = [];
    },
    handleClickOutside(evt) {
      if (!this.$el.contains(evt.target)) {
        this.isOpen = false;
        this.arrowCounter = -1;
      }
    }
  },
  watch: {
    items: function(val, oldValue) {
      // Compare items
      if (val.length !== oldValue.length) {
        this.results = val;
        this.isLoading = false;
      }
    }
  },
  mounted() {
    document.addEventListener("click", this.handleClickOutside);
  },
  destroyed() {
    document.removeEventListener("click", this.handleClickOutside);
  }
};

new Vue({
  el: "#app",
  name: "app",
  components: {
    autocomplete: Autocomplete
  }
});
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}

.autocomplete {
  position: relative;
  width: 130px;
}

.autocomplete-results {
  padding: 0;
  margin: 0;
  border: 1px solid #eeeeee;
  height: 120px;
  overflow: auto;
  width: 100%;
}

.autocomplete-result {
  list-style: none;
  text-align: left;
  padding: 4px 2px;
  cursor: pointer;
}

.autocomplete-result.is-active,
.autocomplete-result:hover {
  background-color: #4aae9b;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
  <autocomplete />

</div>

<script type="text/x-template" id="autocomplete">
  <div class="autocomplete">
    <input type="text" @input="onChange" v-model="search" @keyup.down="onArrowDown" @keyup.up="onArrowUp" @keyup.enter="onEnter" @click="showAll" />
    <ul id="autocomplete-results" v-show="isOpen" ref="scrollContainer" class="autocomplete-results">
      <li class="loading" v-if="isLoading">
        Loading results...
      </li>
      <li ref="options" v-else v-for="(result, i) in results" :key="i" @click="setResult(result, i)" class="autocomplete-result" :class="{ 'is-active': i === arrowCounter }">
        {{ result }}
      </li>
    </ul>

  </div>
</script>

Answer №2

While this technique may not be new, a great way to scroll is by utilizing the scrollIntoView method.

smoothScrolling() {
    currentElement.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' });
},

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

Display a dynamic array within an Angular2 view

I have a dynamic array that I need to display in the view of a component whenever items are added or removed from it. The array is displayed using the ngOnInit() method in my App Component (ts): import { Component, OnInit } from '@angular/core' ...

Set up counters for a variety of Owl Carousel sliders

I am looking to set up multiple owl carousel sliders, where each slider has a counter to track its position. I want the counters to update independently, but I'm running into issues with them not working correctly. Each slider should display a counte ...

Issue with parsing JSON data for heatmap in Mapbox

Here's the code I'm using: heat = L.heatLayer([], { maxZoom: 12 }).addTo(map); $.getJSON("js/example-single.geojson", function(data) { var geojsosn = L.geoJson(data, { onEachFeature: function (feature, layer) { console.log(f ...

Error message indicating a problem with the locator By.linkText that contains dots in Selenium: TypeError - Invalid locator

I've searched through other resources for solutions, but I can't find anything that addresses my specific issue. The error message I'm encountering is TypeError: Invalid locator. Here's a snippet of my code (where I suspect the problem ...

How to send data to res.render in Node.js?

I'm new to working with node.js. In my index.ejs file, I have included a header.ejs file. Everything seems to be functioning properly except for the fact that I am unable to pass values to the variable status in the header.ejs. index.ejs <html& ...

Saving the Chosen Option from Button Group into react-hook-form State

Struggling to save the chosen value from MUI Button Group into react-hook-form's state, but encountering challenges with the update not happening correctly. view codesandbox example Below is a simplified version of my code: import { ButtonGroup, But ...

Ways to detect scrolling activity on the v-data-table module?

Are you looking for a way to detect scrolling events on the v-data-table component in Vuetify framework? I am referring to the scenario where the table has a fixed height, causing the table body to scroll. <v-data-table fixed-header :height=400 : ...

Leveraging jQuery within a method defined in an object using MyObject.prototype.method and the 'this' keyword

Recently, I've started exploring Object-oriented programming in JavaScript and have encountered a challenge. I'm trying to define an object like the example below, where I am using jQuery inside one of the methods. I'm curious about the best ...

Using PHP to extract information from a JSON file

After researching various articles and tutorials, I've managed to piece together the code below. However, as a beginner in PHP, JSON, and Javascript, I am seeking guidance. The task at hand is to update a div with the ID "playerName" every 10 seconds ...

Efficiently accessing and displaying nested models in AngularJS

Currently, I am in the process of developing a website that involves numerous relational links between data. For instance, users have the ability to create bookings, which will include a booker and a bookee, as well as an array of messages that can be asso ...

How can I activate a route without changing the URL in AngularJS?

Is there a way to activate a route and display a different view in Angular without changing the URL? I have integrated an Angular app into an existing website, and I prefer not to modify the URL within my embedded application, but would still like to mana ...

Non-IIFE Modules

Check out this discussion on Data dependency in module I have several modules in my application that rely on data retrieved from the server. Instead of implementing them as Immediately Invoked Function Expressions (IIFEs) like traditional module patterns ...

When a ng-model is added, the input value disappears

i am currently working on a form that contains angular values. <tr ng-repeat="alldata in c.da"> <td>{{alldata.id}}</td> <td><input type="text" class="form-control" value="{{alldata.name}}" ...

Husky 5: The Ultimate Gitignore Manager

Last week, a new version of Husky was released, known as Husky 5. I came across an interesting article discussing the features and updates in this release that can be found here. Upon migrating to Husky 5 (), I discovered a new directory named .husky with ...

Leverage the power of React in tandem with Express

My web site is being created using the Express framework on NodeJS (hosted on Heroku) and I'm utilizing the React framework to build my components. In my project, I have multiple HTML files containing div elements along with React components that can ...

c# simulating button click through injected JavaScript

Greetings, I'm seeking assistance in replicating a specific button click on a website. Here is the code for the button: <button type="button" class="btn btn-link btn-xs" onclick="getComponents('188855', '5a0f44a9d70380.12406536&apo ...

Removing a record from a database using ASP.NET MVC 5

Looking for some insight on the behavior of my JavaScript and Action in the Controller. Below are the current code snippets: Index.chtml @model IEnumerable<WebSensoryMvc.Models.SessionData> @{ ViewBag.Title = "Index"; Layou ...

Transfer Data from a Factory to a Controller in AngularJS

Although it may seem like a simple question, it has taken me nearly 3 hours to try and figure out what went wrong here. Perhaps someone could help identify the issue and provide a solution (it seems like an easy fix, but I'm just not seeing it). So, h ...

Images that adjust to different screen sizes within a grid layout

I have four images that need to be aligned in the following layout: ____________ |1 |4 | |_____| | |2 |3| | |__|__|______| They must be flush against each other, occupy 100% of the viewport's width, and most importantly, be respon ...

Component does not display dynamically created DOM elements

I have a function that creates dynamic DOM elements like this: const arrMarkup = []; const getMarkup = () => { if (true) { arrMarkup.push( <Accordion expanded={expanded === cust.name} onChange={handleChange(cust.name)}> ...