[SalesForce] Unable to Close Drop down menu on Outside click in LWC

I am unable to close the dropdown menu in LWC on clicking anywhere else on the page apart from the dropdown menu . Please find the code below ,

HTML Code :

<a class="userStyle" role="button" href="#" onclick={displayUser}></a>
                            <div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
                                <a class="dropdown-item drop-down" href={profileURL}>User Profile</a>
                                <a class="dropdown-item drop-down" href={STCURL}>Service Terms &amp; Conditions</a>
                                <a class="dropdown-item drop-down" href={logoutURL}>Logout</a>
                            </div>

Javascript Code :

 displayUser(e) {
    e.preventDefault();
    let displayStyle = this.template.querySelector("div.dropdown-menu").style
      .display;
    if (displayStyle === "none" || displayStyle === "") {
      this.template.querySelector("div.dropdown-menu").style.display = "block";
    } else {
      this.template.querySelector("div.dropdown-menu").style.display = "none";

    }
  }

Javscript Code I am trying to add for closing the above mentioned dropdown on outside click in ConnectedCallback() function :

connectedCallback() {
    window.addEventListener("mouseup" , (e) => {
      console.log("Into mouseup");
      let dropdown =  this.template.querySelector("div.dropdown-menu");
      if(e.target != dropdown && e.target.parentNode != dropdown) {
        console.log("Into If");
        dropdown.style.display = 'none';
      }
    });
}

Note : The above addEventListener Function is getting executed on all page clicks , but is not letting me open the dropdown itself as the If Function is getting executed for the Actual Dropdown anchor tag click as well which is preventing the dropdown from opening .

Please help regarding the same and let me know if u need any more details on the same.

Best Answer

To open the dropdown you've used an onclick handler. From your description the dropdown should disappear when clicking outside of that anchor element.

Handle an event when the anchor loses focus by adding onblur handler to the anchor. This event handler should perform the logic that hides the dropdown.

This solution on its own has drawbacks such as the anchor losing focus if you press TAB.

Related Topic