Undo/Redo for Textarea
JavaScript
Hard
3 views
Problem Description
You have , , . Keep history of changes (max 50). Undo/redo should update textarea value.
Output Format
No output (DOM change).
Constraints
Assume #txt #undo #redo exist.
Official Solution
const txt=document.getElementById('txt');const undo=document.getElementById('undo');const redo=document.getElementById('redo');let hist=[txt.value||''];let pos=0;const clamp=()=>{undo.disabled=pos===0;redo.disabled=pos===hist.length-1;};const push=v=>{if(hist[pos]===v)return;hist=hist.slice(0,pos+1);hist.push(v);if(hist.length>50){hist.shift();}pos=hist.length-1;clamp();};let t=0;txt.addEventListener('input',()=>{clearTimeout(t);t=setTimeout(()=>push(txt.value),150);});undo.addEventListener('click',()=>{if(pos>0){pos--;txt.value=hist[pos];clamp();txt.focus();}});redo.addEventListener('click',()=>{if(pos<hist.length-1){pos++;txt.value=hist[pos];clamp();txt.focus();}});clamp();
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!