What is the method to obtain the keycode for a key combination in JavaScript?

    $(document).on('keydown', function(event) {

        performAction(event);
        event.preventDefault();
    });

By using the code above, I am successful in capturing the keycode for a single key press. However, when attempting to use a combination of keys, I am only receiving events for the first and second keys pressed. For example, !(Shift + 1), $(Shift + 4).

Is there a way to retrieve the keycode for combinations of keys?

Answer №2

If you want to enhance the functionality of jQuery's fn Object by incorporating a function that manages triggering callback functions based on key presses and Regex matching, there is a solution.

A while back, I created a similar response. Initially, it only supported regex matching for individual keys, but after some adjustments, it now accommodates multiple key combinations.

$.fn.selectedKey = (function () {
    var keys = "";
    var last = "";
    var key = "";
    return function (cb, data) {
        def.call(data, {
            ctrlKey: 2,
            altKey: 2,
            invert: 0,
            filter: /.*/,
            preventDefault: false
        });

        function validate(e) {
            var exp = new RegExp(e.data.filter.replace(/\\\\(\d)/g, String.fromCharCode("$1")));
            var c = !!(e.data.ctrlKey ^ e.ctrlKey ^ 1 > 0);
            var a = !!(e.data.altKey ^ e.altKey ^ 1 > 0);
            return (exp.test(keys) && (c && a));
        }

        function def(obj) {
            for (var prop in obj) {
                this[prop] = this[prop] || obj[prop];
            }
        }
        this.keypress(data, function (e) {
            key = e.char = String.fromCharCode(e.keyCode || e.which);
            keys += (!!~keys.indexOf(key)) ? "" : key;
            key = key["to" + (e.shiftKey ? "Upper" : "Lower") + "Case"]();
            keys = keys["to" + (e.shiftKey ? "Upper" : "Lower") + "Case"]();
            if (e.data.preventDefault) e.preventDefault();

            if ((validate(e) != e.data.invert) && keys != last) {
                cb(e);
                last = keys;
            }
        });
        if (!this.data("keyupBound")) {
            this.keyup(data, function (e) {
                key = e.char = String.fromCharCode(e.keyCode || e.which);
                var t = keys.toLowerCase().split("");
                t.splice(t.indexOf(e.char), 1);
                keys = t.join("");
                last = keys;
            });
            this.data("keyupBound", true);
        }
    };

})();

$("body").selectedKey(function (e) {
    console.log("All lowercase letters, numbers, and 'A': " + e.char);
}, {
    filter: "^[a-z]|[0-9]|A$",
    ctrlKey: 2,
    altKey: 2
});

$("body").selectedKey(function (e) {
    console.log("KeyCode 2 " + e.char); // Ctrl + b
}, {
    filter: "\\2",
    ctrlKey: 1,
    altKey: 2
});

You can also apply filter:/.{4,5}/ to trigger actions when any 4 to 5 keys are pressed simultaneously

For instance, the following code triggers when A + S + D are pressed together:

$("body").selectedKey(function (e) {
    console.log("ASD has been pressed");
}, {
    filter: "^ASD$",
    ctrlKey: 2,
    altKey: 2
});

Check out a functioning demo on JSBin

Edit Note: Resolved continuous triggering issue when holding keys if validation was true
Edit2: Corrected the usage of the last variable

Answer №3

To keep track of which key was pressed, it is important to utilize both the keyup and keydown events:

var pressedKeys = {};

$(document).keydown(function(event) {
  pressedKeys[event.which] = true;
  // Here you can access all currently pressed keys:
  for (keyCode in pressedKeys) {
    // Loop through and identify which keys are currently pressed
  } 
});

$(document).keyup(function(event) {
  delete pressedKeys[event.which];
});

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

Tips for replacing all occurrences of a specific string in HTML while preserving JavaScript attributes

Is there a way to use RegEx to replace part of an HTML document without affecting the root element or other elements like event listeners? Consider this scenario: for (; document.body.innerHTML.indexOf(/ea/) != -1;) { document.body.innerHTML = docu ...

Styled-Component: Incorporating Variables into Styled-Component is my goal

Currently, I am working on an app and have created a separate file for styling. I decided to use style-components for custom CSS, but faced an issue where I couldn't access variables instead of HEX values. Even after storing color values in a variable ...

When it comes to successful payments, should you use `checkout.session.async_payment_succeeded` or `checkout.session.completed` in the Stripe event?

I'm feeling a little uncertain about the differences between two events: checkout.session.async_payment_succeeded & checkout.session.completed Currently, I am utilizing checkout.session.completed, but I'm wondering if checkout.session.async ...

What is the method to individually determine "true" or "false" using .map() in coding

I am faced with an array of data that needs to be manipulated individually, but it should still function as a cohesive unit. Can you assist me in achieving this? function OrganizeFollow() { const [followStatus, setFollowStatus] = useState([]); co ...

Tips for utilizing the "this" keyword in JavaScript

Here's a snippet of code that I'm having trouble with: this.json.each(function(obj, index) { var li = new Element('li'); var a = new Element('a', { 'href': '#', 'rel': obj ...

Issues with validating the Google Maps API JavaScript tag

Currently working on updating a website to be fully validated with HTML5 using W3C standards. Having trouble validating the Google Maps API JavaScript tag in the code snippet below: <script src="http://maps.googleapis.com/maps/api/js?libraries=places& ...

Observing the innerHTML of a Vue component

Currently, I am utilizing an npm package called vue3-markdown-it to display markdown within some of my content. When the component renders, I need to access its innerHTML and make customized modifications before displaying it in my div. However, there is ...

Two separate tables displaying unique AJAX JSON response datasets

As a beginner in javascript, I am facing a challenge. I want to fetch JSON responses from 2 separate AJAX requests and create 2 different tables. Currently, I have successfully achieved this for one JSON response and table. In my HTML, I have the followi ...

Employing state management in React to toggle the sidebar

A working example of a sidebar that can be toggled to open/close using CSS, HTML and JavaScript is available. Link to the Example The goal is to convert this example to React by utilizing states instead of adding/removing CSS classes. To ensure the side ...

Ensure that autocorrect is set to suggest the nearest possible quantity form in WordPress

I'm currently in the process of creating a webshop using WooCommerce. Our quantity system is a bit unique, as we are using WooCommerce advanced quantity, which means that quantities increase by 0.72 increments (e.g. 0.72, 1.44, 2.16 etc). The +/- butt ...

What could be causing the issue with lodash throttle not functioning correctly in the useWindowSize custom hook?

I'm attempting to implement a resize event with throttle, but I'm encountering an issue. To troubleshoot, I have tried the following: import {throttle} from 'lodash' export function useWindowSize() { const [windowSize, setWindowSize] ...

Developing a two-dimensional JavaScript array using an AJAX PHP request

I've been working with a MySQL table that stores image data. My goal is to extract this image data and store it in a JavaScript array. The fields I need for the array are "image_ref" and "image_name." To achieve this, I understand that I'll nee ...

Applying a class to an element in VueJS is not functioning as expected

My goal is to assign the class .testcolor to the div element when testvalue is true, and apply no class when it's false. I encountered an issue where the getClass method does not get called when added to :class attribute, but works fine when called f ...

What is the top choice for creating a shallow copy of an array

While delving into the vue source code today, I stumbled upon a method of writing that left me puzzled. view source const deduped = [...new Set(pendingPostFlushCbs)] My initial thought is that it is a shallow copy of the array. But why is there a need t ...

Sending multiple unique forms with the same structure using JavaScript and Ajax on a single PHP page

In my PHP page, there are 12 individual forms with unique form IDs, checkboxes, and dropdowns. Take a look at this image: https://i.stack.imgur.com/pODzk.png Each form has an Update Zone that fetches Name, Enable status, Time, Dim information, and sends ...

Modify the image source using Javascript

I need to update the src attribute of an image in a parent element nested within a ul li when a link is clicked. Here's my code so far. I know how to use JavaScript to change the src attribute, but I'm not sure how many levels I need to go up to ...

Setting value in Angular's ng-repeat directive

Utilizing ng-repeat, I am creating a table with radio buttons. The main goal is to assign each radio button a value based on the position of the object in the original array (before any sorting takes place). However, using $index assigns the position in ...

Aligning the 'container-fluid' slideshow and video player

I'm struggling to center a video in a slick slider that is set as a 'container-fluid'. The slideshow and video display fine across the full width of the browser, but when I resize the browser window or view the site on a lower resolution, I ...

Utilizing the power of Vue Router with DataTables

I am currently facing an issue where I want to include links or buttons in my DataTable rows that can navigate to a vue route when clicked. The straightforward approach would be to add a normal <a> element with the href attribute set to "/item/$ ...

Trouble Arising from the Lack of Coordination Between CSS Transition and JavaScript Update Triggered by Element

I'm currently working on a web development project that involves a list of clickable elements. When one of these elements is clicked, it should become active and trigger a CSS transition (such as a transform) with a duration of 200ms. Additionally, I ...