I'm currently facing an issue with two div elements on my webpage. I want only one of them to be visible at a time, depending on which key is pressed. If the 1 key is pressed, I want 'div1' to fadeIn (if it's not already visible) and for 'div2' to fadeOut. On the other hand, if the 2 key is pressed, 'div2' should fadeIn while 'div1' fades out. Below is the code snippet that I have implemented.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#div2").fadeOut();
});
</script>
<script>
$(document).ready(function(){
$(document).keydown(function(e){
if (e.keyCode==49)
$("#div2").fadeOut();
$("#div1").fadeIn();
});
if (e.keyCode==50)
$("#div1").fadeOut();
$("#div2").fadeIn();
});
});
</script>
</head>
<body>
<h1>To toggle visibility, press 1 or 2 keys - 'div1': 1 & 'div2': 2</h1>
<div id="div1">1</div>
<div id="div2">2</div>
</body>
</html>
While this functionality worked well with buttons, it seems to encounter issues when using keypresses. Can anyone help me figure out what mistake I am making?