Junior
How would you implement a dropdown menu and its closing mechanism?
sobes.tech AI
Answer from AI
To implement a dropdown window (for example, for a menu or modal window) and its closing mechanism on a web page, I would use a combination of HTML, CSS, and JavaScript.
HTML:
One trigger element (button, link) and one container element for the dropdown content.
<button id="dropdownTrigger">Open dropdown</button>
<div id="dropdownContent" class="hidden">
<!-- Dropdown content -->
<p>This is a dropdown window.</p>
<button id="closeButton">Close</button>
</div>
CSS:
Hide the dropdown by default and style it.
.hidden {
display: none;
}
#dropdownContent {
position: absolute; /* Or fixed, depending on needs */
background-color: white;
border: 1px solid #ccc;
padding: 10px;
z-index: 100; /* To appear above other content */
}
JavaScript:
Handle click events to open and close the window.
const dropdownTrigger = document.getElementById('dropdownTrigger');
const dropdownContent = document.getElementById('dropdownContent');
const closeButton = document.getElementById('closeButton');
// Open dropdown
dropdownTrigger.addEventListener('click', () => {
dropdownContent.classList.remove('hidden');
});
// Close with button inside window
closeButton.addEventListener('click', () => {
dropdownContent.classList.add('hidden');
});
// Close on click outside the window (event delegation)
document.addEventListener('click', (event) => {
if (!dropdownContent.contains(event.target) && !dropdownTrigger.contains(event.target)) {
dropdownContent.classList.add('hidden');
}
});
// Close on pressing the Escape key
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && !dropdownContent.classList.contains('hidden')) {
dropdownContent.classList.add('hidden');
}
});
Explanation of closing mechanisms:
- Close button inside the window: A simple method, direct
clickevent on the button. - Click outside the window: Event delegation on
document. Checks if the click was not inside the dropdown (dropdownContent.contains(event.target)) or the trigger (dropdownTrigger.contains(event.target)). If outside, the window is hidden. - Pressing the Esc key: Handles
keydownevent ondocument. When the "Escape" key is pressed and the window is visible, it is hidden.
This approach provides several convenient ways to close, enhancing user experience.