title: window.onclick = function(event) only works for first item
body: <p><a href="https://jsfiddle.net/3vr3j1hk/" rel="nofollow noreferrer">Here is a jsfiddle of my complete code, where you can test the functionality of the two modals. Clicking outside the second modal closes it, while clicking outside the first modal does not close it.</a></p>
  
  <p>I have two modal pop-up windows on an HTML page, and after they're opened, they can be closed by clicking outside of the modal with this code:</p>
  
  <pre><code>// When user clicks anywhere outside of the modal, close it
  window.onclick = function(event) {
      if (event.target == modal) {
          modal.style.display = "none";
      }
  }
  </code></pre>
  
  <p>For some reason, this code only works for the second (last) instance of it in my script.js file. You can see that there are really just two blocks of code in this file: the first controls the first modal, and the second controls the second modal. Each instance of the code above is at the end of the block.</p>
  
  <pre><code>// Get modalCompanies
  var modalCompanies = document.getElementById('companiesModal');
  
  // Get button that opens the modalCompanies
  var btnCompanies = document.getElementById("companiesOpen");
  
  // Get &lt;spanCompanies&gt; element that closes the modalCompanies
  var spanCompanies = document.getElementsByClassName("close")[0];
  
  // When user clicks on the button, open the modalCompanies 
  btnCompanies.onclick = function() {
      modalCompanies.style.display = "block";
  }
  
  // When user clicks on &lt;spanCompanies&gt; (x), close modalCompanies
  spanCompanies.onclick = function() {
      modalCompanies.style.display = "none";
  }
  
  // When user clicks anywhere outside of the modalCompanies, close it
  window.onclick = function(event) {
      if (event.target == modalCompanies) {
          modalCompanies.style.display = "none";
      }
  }
  
  
  
  // Get modalPrivacy
  var modalPrivacy = document.getElementById('privacyModal');
  
  // Get button that opens the modalPrivacy
  var btnPrivacy = document.getElementById("privacyOpen");
  
  // Get &lt;spanPrivacy&gt; element that closes the modalPrivacy
  var spanPrivacy = document.getElementsByClassName("close")[1];
  
  // When user clicks on the button, open the modalPrivacy 
  btnPrivacy.onclick = function() {
      modalPrivacy.style.display = "block";
  }
  
  // When user clicks on &lt;spanPrivacy&gt; (x), close modalPrivacy
  spanPrivacy.onclick = function() {
      modalPrivacy.style.display = "none";
  }
  
  // When user clicks anywhere outside of the modalPrivacy, close it
  window.onclick = function(event) {
      if (event.target == modalPrivacy) {
          modalPrivacy.style.display = "none";
      }
  }
  </code></pre>
  
  <p><strong>What is preventing the <code>window.onclick = function(event) { }</code> function at the end of each block from being functional in both blocks?</strong></p>