I want to make it so when someone clicks the escape key it will hide the tag. how would I do that?
Here is my current code:
boxid = "div";
hidden = "false";
window.onkeyup = function(event) {
if (event.keyCode == 27) && hidden = "true" {
document.getElementById(boxid).style.visibility = "block";
hidden = "false"
}
}
window.onkeyup = function(event) {
if (event.keyCode == 27) && hidden = "true" {
document.getElementById(boxid).style.visibility = "hidden";
hidden = "true"
}
}
<center id="div">
<div style="width: 100%;position: fixed;background: white;display: flex;justify-content: center;align-items: center;text-align: center;overflow: hidden;">
<a href="home">
<img src="https://www.freeiconspng.com/thumbs/homepage-icon-png/house-icon-png-white-32.png" width="35px" height="35px">
</a>
</center>
Thank you all for the help! i got many answers, I didn’t notice everything I did wrong, I will check the answers and see what works! Sorry if I wasn’t clear, I was just trying to hide the tag.
5
Answers
Your code is having 2 mistakes
=
, instead of equality check operator==
for doing comparison.Here is the correct code –
Also to improve your code, for
hidden
variable you can use boolean type as it is working as a flag value.Below is the improved code which you can try –
I didn’t understand much what you are trying to do, but your code has some errors, if you want to do a visibility toggle this is the code you need I think
it’s also a better practice (IMO) to have only one "keyup" event function, instead of two, like this:
Here is another take of it improving on previus answers and making the code ES6 (last version of javascript). As well as some comments on the code I added.
Not sure why but unhide was requested as well
a few mistakes with your code
1- You forgot to close your
<div>
tag2- condition is wrong
if (event.keyCode == 27) && hidden = "true" {
the&& hidden="true"
is outside bracket and alsohidden="true"
means you are giving hidden a new value, not asking if the value of hidden is true so you have to use==
for comparisons3- No need for 2
onkeyup
functions, just use and else statementyou can also use
document.getElementById(boxid).style.visibility = "initial";
anddocument.getElementById(boxid).style.visibility = "hidden";