title: Applying Javascript Only Below a Certain Width
body: <p>I have a search form that I use a simple bit of JS on to toggle its display when a button is clicked. </p>
  
  <p>Here's the HTML:</p>
  
  <pre><code>&lt;div id="form-search"&gt;
    &lt;form action="/search" method="post" role="search"&gt;
      &lt;label for="searchbox"&gt;Search&lt;/label&gt;
      &lt;input value="" name="searchquery" id="searchbox" placeholder="Search Site" type="text"&gt;
      &lt;button aria-label="Submit Search" type="submit" tabindex="-1"&gt;
        &lt;img src="/i/misc/searchbutton.gif" alt="Submit Search"&gt;
      &lt;/button&gt;
    &lt;/form&gt;
  &lt;/div&gt;
  
  &lt;a href="#" onclick="toggle_visibility('form-search');"&gt;&lt;img src="search-toggle.gif" /&gt;&lt;/a&gt;
  </code></pre>
  
  <p>And the JS:</p>
  
  <pre><code>&lt;script&gt;
  &lt;!--
  function toggle_visibility(id) {
  var e = document.getElementById(id);
  if(e.style.display == 'block')
    e.style.display = 'none';
  else
    e.style.display = 'block';
  }
  //--&gt;
  &lt;/script&gt;
  </code></pre>
  
  <p>Note: I got the JS from <a href="https://css-tricks.com/snippets/javascript/showhide-element/" rel="nofollow noreferrer">https://css-tricks.com/snippets/javascript/showhide-element/</a>.</p>
  
  <p>What I would like to do is <em>only</em> have this script work on window widths of 984px or narrower. I think the logic would go something like: "if the window width &lt;= 984px AND display = block, change to display = none", but I'm not sure how to stipulate two "ifs" in JS. </p>
  
  <p>So, first question: how do I stipulate both if conditions in my JS?</p>
  
  <p>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.</p>
  
  <p>Second question: is there a way to say in the JS "when screen is resized to >984px, set display = inline"?</p>
  
  <p>Thanks so much for any recommendations! I'm new to JS. :)</p>
  
  <p>Edited for what I ended up with, thanks to the answer from squgeim:</p>
  
  <pre><code>&lt;script&gt;
  &lt;!--
  var WIDTH_LIMIT = 984;
  function toggle_visibility(id) {
    var e = document.getElementById(id);
  
    var windowWidth = window.innerWidth;
  
    if(e.style.display == 'block' &amp;&amp; windowWidth &lt;= 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 &gt; WIDTH_LIMIT) {
      e.style.display = 'inline'
    } else {
        e.style.display = 'none';
    }
  
  });
  //--&gt;
  &lt;/script&gt;
  </code></pre>