-1

So I've got a function to close a modal when clicking anywhere outside of it. This is the code:

var modal = document.getElementById('quickViewModal');

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
      $('.item').removeClass('modal-carousel-fix');
      $('.modal-backdrop').css('display','none')
      $('.quickview-modal').css('display','none');
      $(this).parent().closest('.carousel-inner').css('overflow', 'hidden');
    }
}

The html looks something like this

<div class="modal quickview-modal" id="quickViewModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-body">
        <p>Modal Content</p>
      </div>
    </div>
  </div>
</div>

However, when I change my JS to get the modal by class name instead it stops working.

This is the code:

var modal = document.getElementsByClassName('quickview-modal');

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
      $('.item').removeClass('modal-carousel-fix');
      $('.modal-backdrop').css('display','none')
      $('.quickview-modal').css('display','none');
      $(this).parent().closest('.carousel-inner').css('overflow', 'hidden');
    }
}

My reason for trying to get the modal by class name instead is that as it's a quickview modal for a product there are several of them, so if I get it by ID the code only works for the first item.

MariaL
  • 1,112
  • 2
  • 16
  • 41
  • Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Ivar Aug 12 '18 at 14:32

1 Answers1

0

Because you will have an array elements getting by class name, not only 1 element.

TigerT
  • 52
  • 3