How can I create a dropdown feature in Khan Academy where it disappears when clicked outside but stays visible when clicked inside, using JavaScript/CSS/HTML? The current implementation closes the dropdown even on internal clicks. The code includes an event listener attached to the document's click event to hide the dropdown if the clicked element is not the dropdown itself or the account image. What is causing this issue and how can it be fixed to achieve the desired functionality within Khan Academy's limitations? Here is the attempted code:
// Function to open the account dropdown function openAccdrpdwn() { document.getElementById("acc-drpdwn").style.display = "block"; } // Event listener to open the account dropdown when clicking on the account image document.getElementById('account-signin').addEventListener('click', openAccdrpdwn); // Event listener to close the account dropdown when clicking outside of it document.onclick = function(event) { var dropdown = document.getElementById("acc-drpdwn"); var accountImage = document.getElementById("account-signin"); if (event.target !== dropdown && event.target !== accountImage) { dropdown.style.display = "none"; } };
#account { background-color: rgb(247, 247, 247); width: 175px; height: 300px; border-radius: 17px; position: absolute; top: 68px; left: 408px; box-shadow: 0px 0px 7px 3px lightgray; z-index: 1; } ...
The above code doesn't work correctly as the dropdown still disappears when clicked inside. Any suggestions on how to implement this feature properly within Khan Academy's environment?