I'm working on a project in which a javascript function runs when either 1) a button is clicked or 2) the "return" key is pressed. The javascript function sets a div's visibility to "visible" and changes the "onclick" and "onKeyDown" attributes to run a different function when clicked/pressed a second time.
For example, clicking the button (or pressing return) once will make the div appear, and doing it twice should make it disappear.
The problem is that I cannot figure out how to make the javascript change the "onKeyDown" attribute when the function is triggered. Is this possible?
I based my code off of this answer: Call a function when the enter button is pressed via Javascript
Here is my code so far:
function visible() {
document.getElementById("box").style.visibility = "visible";
document.getElementById("button").onclick = hidden;
document.body.onKeyDown = "if(event.keyCode==13) hidden()";
}
function hidden() {
document.getElementById("box").style.visibility = "hidden";
document.getElementById("button").onclick = visible;
document.body.onKeyDown = "if(event.keyCode==13) visible()";
}
#box {
visibility:hidden;
width:200px;
height:200px;
background:red;
}
#button {
width:120px;
height:50px;
background:lightblue;
}
<html>
<body onKeyDown="if(event.keyCode==13) visible()">
<div id="box"></div>
<div id="button" onclick="visible()" ></div>
</body>
</html>
Clicking the blue box will make the red box appear, and so will pressing return; but pressing return again will not make the box disappear.