I am trying to show a search box when you click the search icon in WordPress. The issue I am having is I want it to hide if you click anyplace else on the site.
Currently this is the code I am using and it works if you click the icon on and off but i want lost focus click also.
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
The other script I was trying to use is this but it doesn’t seem to have any effect.
<script>
document.addEventListener('click', function handleClickOutsideBox(event) {
const box = document.getElementById('myDIV');
if (window.getComputedStyle(x).visibility === "visible") {
x.style.visibility = "hidden";
}
});
</script>
Any help would be great thank you.
The second part of my code
<script>
document.addEventListener('click', function handleClickOutsideBox(event) {
const box = document.getElementById('myDIV');
if (window.getComputedStyle(x).visibility === "visible") {
x.style.visibility = "hidden";
}
});
</script>
I thought this would hide it if it saw it was visible but it isn’t working.
2
Answers
Try Changing ‘visibility’ to ‘display’ in your second and third code pieces.
because you’re controlling your search inputs’ visibility using ‘display’ attribute in the first piece so the ‘visibility’ is quite meaningless.
You can do it like this:
Setting both display and visibility as I’ve shown here is overkill. You only need one of them (they do slightly different things in this context)