Clipboard Copy with Fallback
JavaScript
Hard
3 views
Problem Description
You have #btn and #src (text input). On click copy #src value. Use navigator.clipboard when available, else fallback using a hidden textarea and document.execCommand('copy'). Show result in #msg.
Output Format
No output (DOM change).
Constraints
Assume #btn #src #msg exist.
Official Solution
const btn=document.getElementById('btn');const src=document.getElementById('src');const msg=document.getElementById('msg');const fallback=text=>{const ta=document.createElement('textarea');ta.value=text;ta.style.position='fixed';ta.style.left='-9999px';document.body.appendChild(ta);ta.select();let ok=false;try{ok=document.execCommand('copy');}catch(e){}ta.remove();return ok;};btn.addEventListener('click',async()=>{const text=src.value||'';let ok=false;try{if(navigator.clipboard&&navigator.clipboard.writeText){await navigator.clipboard.writeText(text);ok=true;}else ok=fallback(text);}catch(e){ok=fallback(text);}msg.textContent=ok?'Copied':'Copy failed';});
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!