Kawiesh

Vanilla JS onclick copy w/ fallback

Jan 18th, 2021
681
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let b= document.querySelector('pre'),
  2.     c= 'i am stupid';
  3.  
  4. b.addEventListener('copy',
  5. function(e){
  6. e.clipboardData.setData('text', c);
  7. e.preventDefault();
  8. });
  9.  
  10. b.onclick= function() {
  11. try{ navigator.clipboard.writeText(c);
  12. alert('Copied!');
  13. }
  14. catch(err){
  15.     try{let inp =document.createElement('input');
  16.         document.body.appendChild(inp)
  17.         inp.value= c; inp.select();
  18.         document.execCommand('copy',false);
  19.         inp.remove();
  20.         alert('Copied!!');}
  21.     catch(err){
  22.         try{let e= window.getSelection(),
  23.             f= document.createRange();
  24.             f.selectNodeContents(b);
  25.             e.removeAllRanges();
  26.             e.addRange(f);
  27.             document.execCommand("copy");
  28.             alert('Copied!!!');}
  29.          catch(err){alert("Couldn't copy because: "+ err.message)}
  30.      }
  31. }
  32. };
  33.  
RAW Paste Data