Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Detect Keypress using JavaScript ?
Next article icon

How to make a key fire when key is pressed using JavaScript ?

Last Updated : 24 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, holding down a key will fire the key continuously until it is released. This behavior may be used in applications such as games where a key may be expected to fire only once even after being held down. This can be achieved using two methods: 

Method 1: Using a flag variable to check the current key status: A flag variable is defined which keeps track of the current key press. The ‘keyup’ and ‘keydown’ events are both set to modify this flag variable so that it correctly reflects the current status of the key press. 

The ‘keydown’ event only allows for the respective event to fire if the key is not already held down by checking the flag variable. The ‘keyup’ event on the other hand sets the flag variable to indicate that the key has been released. Using both these with event listeners, one can make sure that the key fires only once even if it is being held down. 

Syntax: 

let isPressed = false;        element.onkeydown = function (e) {      if (!isPressed) {          isPressed = true;          console.log('Key Fired!');      }  };    element.onkeyup = function (e) {      isPressed = false;  }

Example: 

html




<body>    
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        How to make a key fire only
        once when pressed?
    </b>
      
    <p>
        Press any button and observe
        the logs to verify that a key
        only fires once.
    </p>
      
    <input type="text">
      
    <script type="text/javascript">
        let element = document.querySelector('input');
        let isPressed = false;
          
        element.onkeydown = function (e) {
            if (!isPressed) {
                isPressed = true;
                console.log('Key Fired!');
            }
        };
              
        element.onkeyup = function (e) {
            isPressed = false;
        }
    </script>
</body>
 
 

Output: 

using-flags 

Method 2: Using the repeat property: The ‘repeat’ property of the KeyboardEvent interface is used to check if a key is getting repeated as a result of being held down by the user. This property can be checked on every ‘keydown’ event and allow the specified event to only fire if it returns false. This prevents the key from firing multiple times even if the user holds the key down. 

Syntax: 

element.onkeydown = function (e) {      if (!e.repeat) {          console.log(&quot;Key Fired!&quot;);      }  };

Example: 

html




<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        How to make a key fire only
        once when pressed?
    </b>
      
    <p>
        Press any button and observe
        the logs to verify that a key
        only fires once.
    </p>
      
    <input type="text">
      
    <script type="text/javascript">
        let element =
            document.querySelector('input');
              
        element.onkeydown = function (e) {
            if (!e.repeat) {
                console.log("Key Fired!");
            }
        };
    </script>
 </body>
 
 

Output: 

using-repeat



Next Article
How to Detect Keypress using JavaScript ?
author
sayantanm19
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • How to find out which Character Key is Pressed using JavaScript?
    To find which key is pressed in JavaScript, use event listeners like keydown, keypress, or keyup. By accessing properties such as event.key or event.code, it becomes easy to identify the specific key pressed. This approach is useful for handling user input and triggering actions based on key events.
    2 min read
  • How to disable arrow key in textarea using JavaScript ?
    Given an HTML element containing the <textarea> element and the task is to disable scrolling through arrow keys with the help of JavaScript. Approach 1: Add an event listener onkeydown on the window.If the event happens then check if the keys are arrow or not.If arrow key is pressed then preve
    2 min read
  • How to Detect Keypress using JavaScript ?
    In this article, keyboard detection is performed using HTML and CSS. HTML stands for "Hypertext Markup Language". HTML language helps the developer to create and design web page elements like links, sections, paragraphs, headings, and blockquotes for web applications. CSS stands for "Cascading Style
    2 min read
  • How to check whether the META key pressed when event is fired using jQuery ?
    jQuery is a feature-rich JavaScript library. It is a fast and most used JavaScript library. Before using jQuery you must have a basic knowledge of HTML, CSS, and JavaScript. In this article, we will learn about how you can check whether the META key was pressed when the event fired JQuery. META key:
    2 min read
  • How to display a message when given number is between the range using JavaScript ?
    In this article, we will learn to display a message when a number is between the given range using JavaScript. We take a number from the user and tell the user whether it is in between a range or not, in our case, the range is 1 to 10. Approach: We create a button and add a click event listener to i
    1 min read
  • JavaScript Detecting the pressed arrow key
    Sometimes we need to detect the keys and sometimes even detect which keys were pressed. To detect which arrow key is pressed we can use JavaScript onkeydown event. Detecting the pressed arrow key using onkeydown EventThe DOM onkeydown Event in HTML occurs when a key is pressed by the user. Syntax:ob
    2 min read
  • How to check caps lock is on/off using JavaScript / jQuery ?
    The job is to determine the caps lock is turned on or turned off using JavaScript and jQuery. Check caps lock is on/off using JavaScript: addEventListener() Method: This method adds an event handler to the document. Syntax: document.addEventListener(event, function, useCapture) Parameters: event: Th
    6 min read
  • How to Make a Beep Sound in JavaScript?
    To make a beep sound in JavaScript, you can use the Audio object to play a sound file. Approach: Using Audio FunctionUse the Audio function in Javascript to load the audio file. This HTML document creates a simple web page with a heading and a button. When the button is clicked, the play() function
    1 min read
  • How to Change the Button Label when Clicked using JavaScript ?
    Changing the Label of the Button element when clicked in JavaScript can be used to provide more information to the user such as the text of the Submit button will change to the Submitted as soon as the form submission is completed. The below approaches can be used to accomplish this task: Table of C
    2 min read
  • How to Take Screenshot of a Div Using JavaScript?
    A screenshot of any element in JavaScript can be taken using the html2canvas library. This library can be downloaded from its official website. The below steps show the method to take a screenshot of a <div> element using JavaScript. ApproachIn this approach, we will create a blank HTML docume
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences