Simple Tooltip on Hover
JavaScript
Hard
4 views
Problem Description
Elements with attribute data-tip should show a tooltip div near mouse on hover and hide on mouse leave.
Output Format
No output (DOM change).
Constraints
Assume CSS for .tip exists or inline styles can be used.
Official Solution
let tip=null;const show=(text,x,y)=>{if(!tip){tip=document.createElement('div');tip.className='tip';tip.style.position='fixed';tip.style.pointerEvents='none';document.body.appendChild(tip);}tip.textContent=text;tip.style.left=(x+12)+'px';tip.style.top=(y+12)+'px';tip.style.display='block';};const hide=()=>{if(tip)tip.style.display='none';};document.addEventListener('mouseover',e=>{const el=e.target.closest('[data-tip]');if(!el)return;const text=el.getAttribute('data-tip')||'';const move=ev=>show(text,ev.clientX,ev.clientY);el.addEventListener('mousemove',move);el.addEventListener('mouseleave',()=>{el.removeEventListener('mousemove',move);hide();},{once:true});show(text,e.clientX,e.clientY);});
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!