I am try to change the visibility state of a specific div when the user press "s" or any specific key. Below code works just fine however, it toggles the visibility state even when I am typing something in the form or input field. Any suggestions on how I can write a exception or something to stop the function from executing when user is type in a form.
And also how do I toggle the visibility state from visible to hidden when the user press the same key again?
var searchBar = document.querySelector(".search-pop-up");
document.addEventListener("keypress", function (event) {
toggleSearchBar(event.key);
});
function toggleSearchBar(key) {
if (key === "s") {
searchBar.style.visibility = "visible";
}
}
Thank you so much in advance. Have a good day!
You could try to toggle visibility based on element's previous value. You can make sue that if your input is the active element, then shouldn't toggle visibility:
var searchBar = document.querySelector(".search-pop-up");
document.addEventListener("keypress", function (event) {
toggleSearchBar(event.key);
});
function toggleSearchBar(key) {
if (document.activeElement != searchBar && key === "s") {
searchBar.style.visibility = searchBar.style.visibility === "visible" ? "hidden" : "visible";
}
}
.search-pop-up {
visibility: hidden;
}
body {
height: 100%;
width: 100%;
}
<input class="search-pop-up" />
<button>My button</button>
Here is a short brief about the solution. First, get the active element tagName and then check if it is equal to or not equal to any specific tagName and then execute the function below.
To toggle the visibility I set an if statement to check specific values for example "visible" if it is visible then the next line of code will change it to "hidden" and vice versa.
var searchBar = document.querySelector(".search-pop-up");
document.addEventListener("keypress", function (event) {
// Captures the current active element tagName
var currentElement = document.activeElement.tagName;
var currentElementLower = currentElement.toLowerCase();
// Checks if the current active not equal to "input"
if (currentElementLower != "input") {
toogleSearchBar(event.key);
} else {
return false;
}
});
// Toogle the visibility state
function toogleSearchBar(key) {
if (key === "s") {
if (searchBar.style.visibility === "visible") {
searchBar.style.visibility = "hidden";
} else {
searchBar.style.visibility = "visible";
}
}
}
Hope it helps someone new to JavaScript.
I would try adding event.stopImmediatePropagation() in the keydown;
Alternatively, you can return false to stop events propagation
function onsubmit(event) {
return false;
}