Listen to Vue.js event only when it is at the top

I have developed a unique Vue component for touch screen devices that allows users to input pin codes using buttons instead of standard keyboard input. The component also features customizable key mapping, and I would like to extend its functionality to support keyboard input on desktop devices.

However, I am facing an issue where multiple instances of the pin code input component are mounted on the page, resulting in keystrokes being registered by all components simultaneously.

I am currently exploring options to ensure that only the focused component receives keyboard input, while maintaining seamless button functionality on touch screens.

...

data() {
    return {
        value: '',
        keys: [
            { name: '9', code: 'Digit9'},
            { name: '8', code: 'Digit8'},
            { name: '7', code: 'Digit7'},
            { name: '6', code: 'Digit6'},
            { name: '5', code: 'Digit5'},
            { name: '4', code: 'Digit4'},
            { name: '3', code: 'Digit3'},
            { name: '2', code: 'Digit2'},
            { name: '1', code: 'Digit1'},
            { name: '0', code: 'Digit0'},
        ]
    };
},

mounted() {
    window.addEventListener("keypress", e => {
        let result = _.find(this.keys, ['code', e.code]); // Lodash
        if (result) this.value = "" + this.value + result.name;
    });
}

...

https://i.sstatic.net/kZhWJ.png

Thank you for your assistance.

Answer №1

To enable the reception of keypress events on a div wrapper component, you can include the tabindex attribute.

Subsequently, delegate the keypress event handling to this.$el instead of the global window object.

Vue.component('greeting', {
  template: '<div tabindex="1">Welcome to coligo!</div>',
  props: ['name'],
  mounted() {
    this.$el.addEventListener('keypress', (e) => {
      console.log(this.name, e)
    })
  },
  methods: {
  }
});

// Instantiate a new Vue instance and mount it to our designated div element with the id of app
var vm = new Vue({
  el: '#app'
});

Check out the live demo at https://jsfiddle.net/ittus/6b2ru73t/

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

A useful tip for jQuery users: learn how to prevent the context menu from appearing when a text box is

Is there a way to prevent the context menu from appearing in jQuery when the text box is disabled? The right-click disable functionality works well in all browsers except for Firefox. Please note that the right-click disable functionality works when the t ...

The class member was not defined in the asynchronous callback

Let's consider this code snippet: import request = require("request"); class CFoo { test:number; async getItem(): Promise<number> { var requestOptions = { method: 'GET', url: `https://www.goog ...

Complete a bootstrap row and begin a new row after every nth div element

I have a grid layout in Bootstrap that I will be filling with blog post thumbnails. <section class="container"> <div class="row thumbs"> <div class="col-sm-3">content</div> <div class="col-sm-3">content</div> ...

Fetching jQuery library via JavaScript

Having trouble loading the JQuery library from a JavaScript file and using it in a function. JS1.js $(document).ready(function () { //var id = 728; (function () { var jq = document.createElement('script'); jq.type = 'te ...

Implementing the jquery mobile data-native-menu feature in a select element dynamically generated from jeditable

Greetings! I have encountered an issue where the data-native-menu="false" instruction works correctly when directly placed in a select element, but doesn't work when added to a select generated by JavaScript (using the Jeditable plugin). You can view ...

The Vue router is unable to access the store state

My Vue application is utilizing vue-router and vuex. I acquire an authentication token from my API, store it in localStorage, and then push it to the store. However, when the page refreshes, the app is unable to retrieve the token from localStorage and the ...

Using JQuery and Javascript to retrieve information from one drop down list based on the selection made in another drop down

I'm currently working on a project that involves 2 drop-down menus. The first menu allows you to select a general model, while the second menu displays specific models based on your selection. http://jsfiddle.net/QskM9/ Here's an example of how ...

Should scripts be replayed and styles be refreshed after every route change in single page applications (SPA's)? (Vue / React / Angular)

In the process of creating a scripts and styles manager for a WordPress-based single page application, I initially believed that simply loading missing scripts on each route change would suffice. However, I now understand that certain scripts need to be ex ...

Using Vue.js to create multiple instances of a module

I'm still learning Vue 2 and have only been working with it for three days now. My app has product pages and I use Stripe for payments. I found a npm module that I am using here After browsing multiple product pages, it seems like Stripe is creating ...

An issue occurred in React 16.14.0 where the error "ReferenceError: exports is not defined" was not properly

As the creator of the next-translate library, I have encountered a perplexing issue with an experimental version involving an error specifically related to React 16.14.0. Interestingly, upgrading React to version 17 resolves the issue, but I am hesitant to ...

Is there a way to send my form via the submission button inside a modal in ASP.NET MVC?

Although it may seem like a simple question to some, I am struggling with understanding how to implement a submit button that opens a modal and displays user input from a text box. The user can then choose to edit their input or proceed with submitting it. ...

How can we dynamically display a time in hours, minutes, and seconds based on the number of seconds when a Vue page is loaded?

Upon mounting a component, I retrieve the getSecondsUptime field and store it as initialData. My intention is to increment this data every second, however, I'm encountering an issue where an infinite loop warning is triggered along with numerous conso ...

Unable to open new tab using target _blank in React js production build

After attempting to access the link, a 404 error appeared in the live version of react js and triggered an error on the firebase hosting platform. <Link target='_blank' to={'/property-details?id='some_id'}/> ...

Exploring the various viewport sizes in Bootstrap breakpoints

I'm currently working on a responsive cropping tool for multiple devices using cropperjs. Right now, I am estimating the viewport sizes for each bootstrap breakpoint but I need to determine the actual height in order to establish a ratio. You can view ...

Refreshing pane content within Kendo UI Splitview

I am utilizing the Kendo UI splitview. In my setup, I have configured one pane on the left for navigation and another pane on the right for content display. The left pane contains 4 navigation links structured as follows: <div data-role="pane" id="si ...

Trouble with Slides.js jQuery plugin loading properly on Chrome and Safari, works perfectly on Firefox

I have implemented a slideshow plugin from on my website: . The issue I am facing is with its compatibility in different browsers. When viewed in Firefox, the slideshow functions perfectly as expected. However, in Chrome or Safari, the slideshow fails to ...

Is there a way to change an object into a string in JavaScript without using JSON.stringify?

Usually I wouldn't approach it this way, but for the sake of a practice exercise, I am attempting to convert an object without relying on JSON.stringify(). Take a look at the object in question: obj = { num: 0, string: "string", func: function ...

Tips for properly aligning an image within an owl carousel

Currently, I am attempting to center a small image within the owl carousel. While I have managed to center it when it's active and in the center, I'm encountering issues when the item no longer carries the "center" class. You can access Owlcarou ...

What is the best way to access the second array in a JSON object?

I have successfully implemented autocomplete with JSON and PHP. It is working fine, but now I am facing a challenge in retrieving the second array from the JSON data. Below is the script I have used in source.php: <?php $req = "SELECT namaBarang, har ...

How can we programmatically add click handlers in Vue.js?

Currently attempting to add some computed methods to an element based on mobile viewports exclusively. Here is a simplified version of my current project: <a class="nav-link float-left p-x-y-16" v-bind:class={active:isCurrentTopicId(t.id)} @click="onTo ...