Hide and Show Element on Enter Key Press

In this tutorial we will see how to Hide and Show Element on Enter Key Press. The JavaScript keyCode property is used and the code is given below.

keyCode property

keyCode property returns the unicode value of the key that has triggered the onkeypress, onkeydown or onkeyup event.

Firefox browser doesn't support keyCode property, so we can use which property for it.

KeyboardEvent which Property

KeyboardEvent which Property also returns the unicode of the key pressed just like the keyCode property.

IE8 and earlier versions of Internet Explorer don't support which property so we can use keyCode property for them.

We can use both keyCode and which property simultaneously so that the code runs on all types of browsers, see the code below.


A div is used in this example, HTML Code is given below.

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Hide and Show Element on Enter Key Press</title>
<div style='background-color:red; padding:40px;' id='div'></div>

JavaScript Code

JavaScript Code is given below.

document.addEventListener("keydown", function(){
var x=event.keyCode || event.which;
var y = document.getElementById("div");
if (y.style.display === "block")
document.getElementById("div").style.display = "none";
document.getElementById("div").style.display = "block";


Press Enter Key to hide and display the following div.

Video Tutorial

Watch video tutorial on how to Hide and Show Element on Enter Key Press.

JavaScript Hide Button After Click Simple Click and Hold Effect Using JavaScript JavaScript Select All HTML Elements Whose ID Start With Same String Count Checked Checkboxes of Specific Form with JavaScript Enable and Disable Button using JavaScript Add Class to HTML Tag On Click using JavaScript Change Class of HTML Tag Using JavaScript Get All Options In Select Tag using JavaScript Replace a Word from everywhere in a String using JavaScript Execute a Function on Hover Using JavaScript Open Select File Dialog Box Using JavaScript Display Message When File Is Selected Using JavaScript Get Clicked HTML Element Name Using JavaScript Get Class of Clicked Element Using JavaScript Count Number of Rows in Table using JavaScript Move Background Image with Mouse Using JavaScript Disable Text Selection Using JavaScript Get Selected Radio Button Value On Click using JavaScript Get input Element Value On Click Using JavaScript Toggle Text of HTML Element with JavaScript onclick