Tuesday, September 24, 2024
Google search engine
HomeLanguagesJavascriptHow to Detect Keypress using JavaScript ?

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 the web pages elements like links, sections, paragraphs, headings, and blockquotes for web applications. CSS stands for “Cascading Style Sheet”. Cascading style sheets are used to design web page layouts. The styles are defined to give styles to tables, sizes, and texts. JavaScript is a scripting programming language used on the client and server side which makes the web pages talk and communicate with each other. All of the above technologies are used to implement keypress detection. Program editor applications like Atom or Sublime Text can be used to compile the programs.

Example: In this example, we will create a program to detect keypress using Javascript.

html




<html
<head
    <link rel="stylesheet" type="text/css"
    href="main.css"
    <script type="text/javascript" src="main.js"
    </script
</head
<body
    <div id="demo"></div
</body
</html>


CSS




body{
    font-family: monospace, arial;
    font-size: 38px;
    text-align: center;
}


Javascript




window.onload = function(){ 
    var demo = document.getElementById('demo'); 
    var value = 0; 
    var space_bar = 32; 
    var right_arrow = 39; 
  
    window.onkeydown= function(gfg){ 
        if(gfg.keyCode === space_bar){ 
            value++; 
            demo.innerHTML = value; 
        }; 
        if(gfg.keyCode === right_arrow) 
    
        alert("Welcome to GeeksForGeeks!"); 
    }; 
    }; 
};


Here,

var space_bar = 32 

and

var right_arrow = 39 

are actually the key codes that correspond to the specific key. Whenever the space bar or the right arrow is clicked, the HTML will detect the type of click and respond by the number of times clicked or by a message.

Output: A number gets displayed when the space bar is once clicked. When the right arrow is clicked, the page responds with a message. Click here to check the live output.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments