Navigating through div elements using arrow keys in Vue

Trying to navigate through div elements using arrow keys is proving to be a challenge for me. I have successfully achieved it in JavaScript, but I am facing difficulties doing it the "vue way". Although there should be no differences, it simply does not work.

I have created a sandbox for anyone to analyze what is happening. It works fine when I am not using Vue.

When attempting to implement this in Vue, I encounter the following error due to this line:

Cannot read property 'focus' of null

document.activeElement.parentNode.previousSibling.firstChild.focus();

Could someone please point out what I am missing? Is the v-for causing the issue, or are there other underlying problems?

Answer №1

It truly depends on the purpose behind needing a focus. If it's simply for highlighting a particular element, consider using a secondary variable to keep track of the current highlight and apply a class to it instead.

https://codesandbox.io/s/300vxzkyk5

<template>
  <div>
    <input ref="input" type="text" @keydown="test" tabindex="0">
    <div ref="test" v-for="item, index in items" :class="{ focus: index === focus }">
       <div>{{ item.title }}</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { title: "First" },
        { title: "Second" },
        { title: "Third" }
      ],
      focus: null
    };
  },
  methods: {
    test: function(event) {
      switch (event.keyCode) {
        case 38:
          if (this.focus === null) {
            this.focus = 0;
          } else if (this.focus > 0) {
            this.focus--;
          }
          break;
        case 40:
          if (this.focus === null) {
            this.focus = 0;
          } else if (this.focus < this.items.length - 1) {
            this.focus++;
          }
          break;
      }
    }
  }
};
</script>

<style>
div.focus {
  border: 1px solid blue;
}
</style>

Answer №2

Have you considered utilizing a data-driven strategy for this situation?

Imagine you have a collection of items. Each item can have an active attribute that can be toggled to either true or false.

By using the up and down keys, you can navigate through the array and automatically set the current item to true. This method eliminates the need for any DOM manipulation.

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

Error in NVD3 causing charts to be inaccurately rendered

While utilizing a stacked area chart in the Stacked display mode, there appears to be an issue with the shading under the graph, particularly on the left side of the displayed plot below. We are currently working with d3 v3.4.9 and nvd3 v1.1.15b. Do you ...

There seems to be an issue with the functionality of Array.filter when trying to use it with arrays

I am facing an issue with filtering branchId from an Array. Here is the code snippet and steps I have taken. const [branchID,setBranchID]=React.useState([]); const tempTwo=[ { branchId: "61b25e0ae177d62ce4cb3b47", bra ...

Ways to resolve the error "Uncaught TypeError: data.map is not a function"

Currently developing an app using reactJS and encountering the following error in the console when using the map function: TypeError: data.map is not a function. Despite successful API data calling as confirmed by console.log, the error persists when tryin ...

Create a personalized Command Line Interface for the installation of npm dependencies

I am looking to develop a Node CLI tool that can generate new projects utilizing Node, Typescript, Jest, Express, and TSLint. The goal is for this CLI to create a project folder, install dependencies, and execute the necessary commands such as npm i, tsc - ...

I'm having trouble with my basic routing set up and I'm struggling to understand why it's not working

I'm currently working on a node tutorial and facing some challenges with my routes.js file. Previously, everything was functioning well today as the Node server was able to read the file. However, it seems to be ignoring it now for some unknown reaso ...

By harnessing a JSON response

After sending an ajax request, the server's response is as follows: {"error":false,"success":true} The ajax code used: $.ajax({ url: '/update', type: 'post', data: $(this).serialize(), success: function(response) ...

The failure of Vuetify's fast fail feature is not stopping the submission of the form

When using Vuetify, fast fail checks will display the error message, but the form is still sent despite the error. <script setup> import { ref } from "vue" const lastName = ref('') const lastNameRules = [ value => ...

Obtaining Spotify API access token using JavaScript code on the front end

I've developed a web application that enables users to generate a list of songs by artists related to a selected artist. The goal is to link the user's Spotify account and create a playlist based on this generated song list, which requires obtain ...

The Backbone Model is producing unspecified data

Having crafted a backbone model, it looks like this: var note_model = Backbone.Model.extend({ default : { HistoryKey : "", InsertDate : "", MemberKey : "", NoteDate : "", ContactNote : "", User ...

Checking for the presence of a certain key within an object containing arrays that are value-based rather than index-based, using a Javascript

As I've been exploring various code snippets to check for the presence of object keys within arrays, I came across some brilliant examples that have been really helpful... However, my current dilemma lies in dealing with a JSON response that requires ...

use ajax to dynamically load a section of the webpage based on filter criteria

I need to implement a search filter using 3 checkboxes. The search results will be displayed in the div with the id=posts_results <div class="checkbox"> <label><input type="checkbox" id="id1" class="typePost" value="En groupe"> ...

There is an array present with data filled in, but unfortunately, I am unable to retrieve specific elements

As I work on my WordPress 4.7.2 website, I find myself making an AJAX call. The PHP function handling this call returns an array using wp_json_encode(). When I view the data array in the success callback of the AJAX function, everything looks just as expec ...

Alter the color of the initially chosen option in the dropdown selection

I'm struggling to modify the color of the initial selection while keeping the remaining selection-options at their default black color. Unfortunately, I haven't been successful in achieving this. Currently, all colors are #ccc. What I want is fo ...

end the node.js automated testing process

I'm currently using Jasmine and Zombie JS to create automated tests. I have integrated Drone.io for Continuous Integration, and the tests are executing successfully. However, there seems to be an issue where after passing the tests, the process does n ...

Learn how to retrieve specific user information from a JSON file by implementing a button click feature within a custom directory using Angular.js

I am just starting to learn angular.js and I'm trying to figure out how to retrieve JSON data from a custom directory. My goal is to display the information of a specific user when a particular button is clicked, but so far I haven't been success ...

Retrieve the script's location from the server prior to the initialization of Angular

Is there a way to dynamically add a script in the index.html page based on the application version? I have a controller that retrieves the app version and attempted to achieve this using AngularJS: var resourceLoader = angular.module('MyTabs&apo ...

Using Javascript to Implement Pinch Zoom on Android

After searching through the depths of the internet, I have yet to come across a viable solution or answer. The challenge at hand is the need to implement pinch zoom functionality for an element (specifically an image) using JavaScript in a Phonegap environ ...

Set a string data type as the output stream in C++

I have a method called prettyPrintRaw that seems to format the output in a visually appealing manner. However, I am having trouble understanding what this specific code does and what kind of data it returns. How can I assign the return value of this code t ...

Organize information by time intervals using JavaScript

I am currently facing an issue where I need to dynamically sort data from the server based on different fields. While sorting is working flawlessly for all fields, I am encountering a problem with the time slot field. The challenge lies in sorting the data ...

Top approach for triggering and re-triggering AJAX using php

I'm in the process of deciphering instructions from my developer. Our approach may not be entirely correct, so I want to ensure that we are on the right track. This is our objective: On a webpage, there exists a button. When this button is clicked, I ...