I have a search form that I use a simple bit of JS on to toggle its display when a button is clicked.
Here's the HTML:
<div id="form-search">
<form action="/search" method="post" role="search">
<label for="searchbox">Search</label>
<input value="" name="searchquery" id="searchbox" placeholder="Search Site" type="text">
<button aria-label="Submit Search" type="submit" tabindex="-1">
<img src="/i/misc/searchbutton.gif" alt="Submit Search">
</button>
</form>
</div>
<a href="#" onclick="toggle_visibility('form-search');"><img src="search-toggle.gif" /></a>
And the JS:
<script>
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//-->
</script>
Note: I got the JS from https://css-tricks.com/snippets/javascript/showhide-element/.
What I would like to do is only have this script work on window widths of 984px or narrower. I think the logic would go something like: "if the window width <= 984px AND display = block, change to display = none", but I'm not sure how to stipulate two "ifs" in JS.
So, first question: how do I stipulate both if conditions in my JS?
Then, I will need to "reset" the display to inline for window widths over 984px, so if someone resizes their window the search form will always display, even if they had hidden it with the JS at a narrower width.
Second question: is there a way to say in the JS "when screen is resized to >984px, set display = inline"?
Thanks so much for any recommendations! I'm new to JS. :)
Edited for what I ended up with, thanks to the answer from squgeim:
<script>
<!--
var WIDTH_LIMIT = 984;
function toggle_visibility(id) {
var e = document.getElementById(id);
var windowWidth = window.innerWidth;
if(e.style.display == 'block' && windowWidth <= WIDTH_LIMIT) {
e.style.display = 'none';
} else {
e.style.display = 'block';
}
}
window.addEventListener('resize', function (e) {
var currentWidth = window.innerWidth;
var e = document.getElementById('form-search');
if (currentWidth > WIDTH_LIMIT) {
e.style.display = 'inline'
} else {
e.style.display = 'none';
}
});
//-->
</script>