What's the best way to activate multiple functions when the same key is pressed repeatedly?

I encountered a challenge while trying to set up different functions for the same key press event. Specifically, I wanted to call function1 when the space key was pressed once, function2 when it was pressed twice, and function3 when pressed thrice.

Despite having the code below, it seems that my last two 'if' statements are never being triggered. Any suggestions on how to resolve this issue? Appreciate any help!

document.addEventListener("keydown", function (e) {
    if (e.code == "") {
      function1();
      if (e.code == "") {
        function2();
      
      } 
      if (e.code == "") {
        function3();
      
      } 
    }

Answer №1

Events in JavaScript are crucial as they activate a function whenever a specific action takes place. It's important to ensure that there is a trigger for these functions to be executed. For instance, if you wish to execute multiple functions upon pressing a key, it's necessary to associate other functions with that key press event. Without additional bindings, simply having a key press event won't enable the execution of multiple functions simultaneously. However, by making some adjustments in the code, it is possible to achieve this multi-functionality.

Illustrated below is an example demonstrating how this can be accomplished.

HTML:

<p class='p'>Hello<p>

CSS:

.red{
  background:red;
}
.green{
  background:green;
}
.blue{
  background:blue;
}

JS:

let v=0
const p = document.querySelector('.p')
document.body.onkeydown= function (e) {
    if (e.keyCode == 32) {
      switch(v % 3){
        case 0:
          p.classList.add('red')
          p.classList.remove('green')
          p.classList.remove('blue')
          v += 1
          console.log(v)
          break
        case 1:
          p.classList.add('green')
          p.classList.remove('red')
          p.classList.remove('blue')
          v += 1
          break
        case 2:
          p.classList.add('blue')
          p.classList.remove('green')
          p.classList.remove('red')
          v += 1
          break
      }
    }
  }

This implementation ensures that another function operates discreetly to select the desired functionality.

Answer №2

To ensure that your event handler functions are not called multiple times for the same event, it is recommended to implement a debounce function. This function involves setting a timer and keeping track of how many times the event has occurred within a specific time frame.

One approach is to create a helper function that manages the delayed execution of your three event handler functions.

const debounceKeyPress = (keyCode, ...fns) => {
    let noOfOccurrences = -1;
    let timeout;

    return (ev) => {
        if (ev.keyCode !== keyCode) {
            return;
        }

        noOfOccurrences += 1;
        clearTimeout(timeout);

        if (fns[noOfOccurrences]) {
            timeout = setTimeout(() => { fns[noOfOccurrences](ev); noOfOccurrences = -1; }, 500);
        }
    }
}

This function accepts a key code and any number of functions, providing flexibility in the number of functions passed. The returned function can then be used as an event listener.

const fn1 = (ev) => console.log(`key ${ev.keyCode} was hit once.`);
const fn2 = (ev) => console.log(`key ${ev.keyCode} was hit twice.`);
const fn3 = (ev) => console.log(`key ${ev.keyCode} was hit three times.`);

document.addEventListener('keydown', debounceKeyPress(32, fn1, fn2, fn3));

You can adjust the timing parameter in the setTimeout function to determine the optimal delay for your specific use case. Additionally, you can include this parameter as an argument in the debounceKeyPress function for more customization options.

Feel free to experiment with different settings to find the best solution for your needs.

Best regards, A.

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

Images within a row element do not decrease in size when the screen is resized

I am in the process of creating a small website aimed at helping my daughter (and other children) learn new words. The illustration demonstrates how I envision the website looking across all types of devices. My initial attempt was based on a template an ...

"Exploring the power of AngularJS Directive, leveraging ng-repeat, and enhancing functionality with

I have a dedicated section in my HTML file where I display testimonials using flexslider. Here is the structure of the markup: <section class="testimonials"> <div class="row"> <div class="small-12 column"> <div class="fle ...

Changing the Size of an Image using HTML and CSS

Does anyone know how to resize images using CSS in an external style sheet instead of directly in the HTML document? I've tried searching on W3Schools but haven't been able to find a solution. I want to maintain consistent styling by resizing im ...

Prevent redirection on buttons within ionic lists

THE ISSUE: I am facing an issue in my Ionic app where I am using the ion-list component. Each item in the list can be swiped to reveal a button (add/remove to favorites). Additionally, each item serves as a link to another page. The problem arises when ...

Is it possible to modify the value of a non-HTML attribute in an input field using jQuery?

I have a text input field that looks like this: <input type="text" value="" somethingSpecial="filename.txt" id="myID" class="box"> There is also a select list as shown below: <select name="type" class="form-select" id="type"> <option ...

AngularJS incorporating dynamic stylesheets

I am facing a challenge with my AngularJS application as it fetches data via an API and dynamically builds a webpage. Typically, I rely on ng-style for dynamic styling, but now I need to utilize the nth-of-type attribute which can only be applied in a CSS ...

Using jQuery to gradually decrease the opacity of a variable

I'm attempting to fadeOut a variable that includes the classes I provided: var elementsToFadeOut = "'.slider-bg , .inner-content , .about-app , .contact-us'" $('.menu-li.a').click(function() { $(elementsToFadeOut).fadeOut(300) ...

Has anyone figured out the issue with Uplodify? It suddenly ceased to function

For some time now, I've been using uplodify without any issues. Unfortunately, as of yesterday, it suddenly stopped working. I'm at a loss as to what might have caused this sudden change. Could someone please offer me some assistance? I've ...

What is the method for setting a cell's row-span to 2 using bootstrap?

Is there a way to make the red cell in a Bootstrap grid have a row-span=2 and fill the second row as well? .cell {height: 100px; border: 1px solid; border-collapse:collapse;} .red {background: red;} .yel {background: lightyellow;} <link href="https:/ ...

Prevent global backorders for products in WooCommerce, including within the admin settings

I am curious about how to globally disable backorders in WooCommerce. I came across some helpful resources: How to disable globally backorders in WooCommerce Currently, I am using add_filter( 'woocommerce_product_backorders_allowed', '__re ...

Avoiding repeated execution of event handlers in subviews of Backbone

Working with Backbone, I have a list container view that should house multiple section views with event handling. However, the issue is that the event is triggered as many times as there are subviews inside the container. I understand that moving the clos ...

Identifying geometric coordinates within Canvas

Currently, I am adding drag and drop functionality to my HTML5 Canvas application. I have encountered a challenge in determining how to detect if the shape being clicked on is not a rectangle or square. For instance, within my 'mousedown' event h ...

CSS animations can manipulate the rate at which frames are displayed

Exploring the use of CSS animation instead of animated GIFs for loading wheels. Check out a simple example here. #me { -webkit-animation: rotation 2s infinite linear; } @-webkit-keyframes rotation { from {-webkit-transform: rotate(0deg);} to ...

Alter the button's color seamlessly while staying on the same page

I have implemented a feature that allows me to change the category of photos without having to leave the page and it works perfectly. My next goal is to create a button system where the pre-defined category of a photo is indicated by a button with a green ...

Saving attribute values in AngularJS by default

My custom tags use 'repairwidth' with the 'width' attribute to get input. The width is determined by the size. The first repairwidth tag always has a width of 50. The second and third repairwidth tags have a dynamic width based on "{ ...

How come certain jQuery scripts and icons are not functioning properly after the partial view is loaded in ASP.NET Core?

I am encountering an issue on my page where I have a list of information that can be searched using fields and Ajax. When I reload the information as a partial view, none of the jQuery code seems to work after the reload. What could be causing this problem ...

Developing a new class within a function

In this section of the HTML file, I have set up a form to collect email and password information from new users in order to create a new profile: <form name="userInfo"> <fieldset> <legend>Create a new account</legend> ...

problem arising from the box shadow and transparent areas of an image

I'm facing an issue while attempting to apply a box-shadow effect on my image. The problem arises due to certain transparent parts of the image causing unexpected results with the box-shadow. To better understand the situation, refer to the code snipp ...

The minification of HTML scripts may cause problems with the <script> tag

Greetings! I have a PHP script that is used to minify the page by removing any comments or spaces. Here is the script: <?php function sanitize_output($buffer) { $search = array( '/\>[^\S ]+/s', '/[^&b ...

Getting the FormArray value in an Angular TypeScript file

Having trouble accessing the form array value in my TypeScript file - it's coming up as a blank array. Here's my HTML code: <mat-form-field class="example-full-width" > <mat-label>Locations </mat-lab ...