MeetCode
Home
Doubts
Why is my C function not returning the …
Solved
1
49
Ask Doubt
View All Doubts
Solvers Leaderboard
Tutorials
Quiz
All Tests
Leaderboard
My Tasks
User Login
Dark
Enable Notifications
Toggle navigation
Keyboard Navigation Dropdown
JavaScript
Hard
3 views
Back to Questions
View Answer
0
Previous
Auto Number Headings with MutationObserver
Hard
P
Next
Clipboard Copy with Fallback
Hard
N
Problem Description
You have
with and
..
. Implement open/close and keyboard: Enter/Space opens, ArrowDown/ArrowUp moves focus inside list, Esc closes.
Input Format
No input.
Output Format
No output (DOM change).
Constraints
Assume one dropdown .dd exists with required elements.
Official Solution
const dd=document.querySelector('.dd');const btn=dd.querySelector('.dd-btn');const list=dd.querySelector('.dd-list');const items=()=>[...list.querySelectorAll('li')];const open=()=>{dd.classList.add('open');};const close=()=>{dd.classList.remove('open');btn.focus();};btn.addEventListener('click',()=>{dd.classList.toggle('open');});btn.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();open();const it=items();(it[0]||list).focus();}if(e.key==='ArrowDown'){e.preventDefault();open();const it=items();(it[0]||list).focus();}});list.addEventListener('keydown',e=>{const it=items();const cur=it.indexOf(document.activeElement);if(e.key==='Escape'){e.preventDefault();close();}else if(e.key==='ArrowDown'){e.preventDefault();(it[Math.min(it.length-1,cur+1)]||it[0])?.focus();}else if(e.key==='ArrowUp'){e.preventDefault();(it[Math.max(0,cur-1)]||it[0])?.focus();}else if(e.key==='Enter'){e.preventDefault();dd.classList.remove('open');btn.textContent=document.activeElement.textContent;btn.focus();}});document.addEventListener('click',e=>{if(!dd.contains(e.target))dd.classList.remove('open');});
Please
login
to submit solutions and comments.
Solutions (0)
No solutions submitted yet. Be the first!
Discussion (0)
No comments yet. Start the discussion!
Prev
Next
Fullscreen Editor
0 lines • 0 chars
Esc close • Tab indent
No comments yet. Start the discussion!