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

Establishing the folder organization for Express Handlebars

I work with NodeJs, Express, and Handlebars. The main file for my server is named app.js const express = require('express'); const exphbs = require('express-handlebars'); const app = express(); app.engine('handlebars', ex ...

Transforming an older React website with react-helmet-async

I am working on a React site that is client-side rendered and I want to use the react-helmet-async module (version 1.0.7). Here's my scenario in the React app: /public/index.js: <head> <title>My title in the index file</title> ...

Remove all HTML tags except for those containing a specific class

Looking for a regex that removes all HTML tags except the "a" tags with the "classmark" class For example, given this HTML string: <b>this</b> <a href="#">not match</a> <a href="#" target="_blank" ...

How to switch around div elements using CSS

There are two unordered list items in a container div and one swap button. When the swap button is clicked, the order of items needs to change. This functionality can be achieved using the following swap function. var ints = [ "1", "2", "3", "4" ], ...

Use JavaScript to switch the h1 title when selecting an option from the dropdown menu

As a beginner in coding, I am struggling to find a solution using an if statement for this particular problem. Although I can achieve the desired result with HTML code and options, this time I need to use arrays and an if function. My goal is to create a ...

Retrieve information dynamically from a JSON file using the get JSON function and iterate through the data

I possess a JSON file that I wish to utilize in creating dynamic HTML elements with the JSON content. Below is the provided JSON data: { "india": [ { "position": "left", "imgurl":"3.jpg" }, { ...

HeaderView in Angular Framework

When exploring the best practices for organizing an AngularJS structure, I came across the recommendation to implement partial views as directives. Following this advice, I created a directive for my app header. In my specific header design, I included a ...

What is the best way to ensure that a task is performed only once the DOM has finished loading following an AJAX request

<div id="mydiv"> ... <a id="my-ajax-link"> ... </a> ... ... <select id="my-selectmenu"> ... </select> ... </div> Upon clicking the 'my-ajax-link' link, it triggers an AJ ...

What is the best way to connect my products on an ecommerce site with hundreds of images?

Despite thoroughly searching the internet, I have been unable to find a solution to my dilemma. I am creating a platform that showcases a lengthy list of products on the website. Additionally, I have a database of pictures stored locally that need to be ...

Pressing the Like Button triggers the transfer of a specific variable from PHP to jQuery

I have a piece of PHP code that I am using to display all users' posts, each with its own unique 'like' button: $sql = "SELECT * FROM posts"; $result = mysqli_query($con,$sql); while($row=mysqli_fetch_assoc($result)){ $post_content = $ro ...

Display a message stating "No data available" using HighCharts Angular when the data series is empty

My Angular app utilizes Highchart for data visualization. One of the requirements is to display a message within the Highchart if the API returns an empty data set. I attempted a solution, but unfortunately, the message does not appear in the Highchart a ...

Tips for displaying an associative object array as td elements within a tbody in Nuxt

I'm having trouble displaying the property of an associative object array in my code. I attempted to utilize a v-for loop and wanted to showcase the property information within the td elements of a tbody. I am aware that v-data-table components have a ...

React version 0.13.3 is throwing an error stating that the Super expression must be either null or a function, not an

I am encountering an issue with the following code snippet: import React from 'react'; import Component from 'react'; import Bar from './Bar.es6.js'; import Chart from './Chart.es6.js'; import { connect } from &apos ...

Guide to Wrapping Inner or Wrapping All Elements Except for the Initial Div Class

I am looking to enclose all the elements below "name portlet-title" without including other elements within the "div class name portlet-title". I have attempted the following methods: 1) $("div.item").wrapAll('<div class="portlet-body"></div ...

What is the reason behind my difficulty in opening my dialog box modally using JavaScript?

I am looking to keep a dialog open while data is being fetched from the server. Here is the code I have written: (async()=>{ document.getElementById("dialog").showModal(); if(condition1 is true){ await server_call1(); } ...

Create fluidly changing pictures within varying div elements

Hello there! I have a form consisting of four divs, each representing a full page to be printed like the one shown here: I've successfully created all the controls using AJAX without any issues. Then, I load the images with another AJAX call, and bel ...

Working with Garber-Irish in Rails: Streamlining Administration and Keeping Code DRY

I am currently implementing the innovative garber-irish technique to organize my JavaScript files. Here's my issue: I have a Model (let's call it Item) with an init function located in app/assets/javascripts/item/item.js For example: MYAPP.ite ...

load a file with a client-side variable

Is there a way to load a file inside a container while utilizing an argument to fetch data from the database initially? $('#story').load('test.php'); test.php $st = $db->query("select * from users where id = " . $id); ... proce ...

The animation of react-circular-progressbar is experiencing a slight delay of one second

I managed to create a circular progress bar with a timer and a button that adds +10 seconds to the timer. However, I'm facing a 1-second delay in the animation of the progress bar when clicking on the button. If anyone could assist me in resolving t ...

Issue with updated form input failing to submit the latest value

Below is my Vue template code: <form action="[path]/post.php" ref="vueForm" method="post"> <input type="hidden" name="hiddenfield" :value="newValue"> <input type="button" value="new value and submit" @click="changeVal(456)"> </form> ...