Home > Back-end >  Dropdown content isn't disappearing on clicking outside
Dropdown content isn't disappearing on clicking outside

Time:06-22

Here's my code: https://codepen.io/hell_cell20/pen/zYRXggJ

On clicking on ellipsis the dropdown content appears but it only disappears on clicking on ellipsis again.

I added this code to hide the dropdown content on clicking anywhere outside dropdown content but it doesn't work:

window.onclick = function(event) {
  if (!event.target.matches('.ellipsis-btn')) {
    var dropdowns = document.getElementsByClassName("ellipsis-content");
    var i;
    for (i = 0; i < dropdowns.length; i  ) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('d-block')) {
        openDropdown.classList.remove('d-block');
      }
    }
  }
}

After adding it, the dropdown content doesn't even appear on clicking on ellipsis - Uncomment the last 12 lines in my codepen's js column to see this.

CodePudding user response:

I was able to get it working in your codepen by doing this.

document.onclick = function(event) {
      if (!event.srcElement.classList.value.includes("fa-ellipsis")) {
         console.log("clicked outside");
        var dropdowns = document.getElementsByClassName("ellipsis-content");
         console.log(dropdowns);
        for (i = 0; i < dropdowns.length; i  ) {
          var openDropdown = dropdowns[i];
          console.log(openDropdown.classList.contains('d-block'));
          if (openDropdown.classList.contains('d-block')) {
            openDropdown.classList.remove('d-block');
          }
        }
      }
    }

CodePudding user response:

Something like this could help you:

window.onclick = function(event) {
  if (!event.target.matches('.fa-ellipsis')) {
    var tweet1El = document.getElementById('tweet-1');
    var tweet2El = document.getElementById('tweet-2');
    // check for focus
    if(!tweet1El.contains(document.activeElement) || !tweet2El.contains(document.activeElement)){
      document.getElementById("tweet-1").classList.remove("d-block");
      document.getElementById("tweet-2").classList.remove("d-block");
    }
  }
}

If the final goal is hide all dropdowns with ellipsis-content class this could help as well:

$(document).on('click', function(event) {
  if (!$(event.target).closest('.ellipsis-btn').length) {
    $('.ellipsis-content').removeClass("d-block");
  }
});
  • Related