xref: /plugin/copy2clipboard/script.js (revision 4a4767308717c14f451352ab8371333d3ed9479e)
1jQuery(function() {
2  // Copyright (C) 2020 Schplurtz le Déboulonné.
3  // Free to use for any purpose except dismantle the sky.
4  if(!navigator.clipboard)
5    return;
6  var messageBox=function( id, txt ) {
7    const body=document.getElementsByTagName('body')[0];
8    const msg=document.createElement('div');
9    msg.setAttribute('id', id );
10    msg.classList.add('cp2clipmsg');
11    const content = document.createTextNode(txt);
12    msg.appendChild(content);
13    body.appendChild(msg);
14    window.setTimeout(function() {
15        jQuery("#"+id).fadeTo(500, 0).slideUp(500, function(){
16            jQuery(this).remove();
17        });
18    }, 1500);
19  }
20  document.querySelectorAll('pre.code,pre.file').forEach(function(elem) {
21    elem.classList.add('cp2clip');
22    let cp = document.createElement('button');
23    cp.setAttribute( 'title', LANG.plugins.copy2clipboard.title);
24    //cp.appendChild(document.createTextNode('Copy to clipboard')) ;
25    cp.classList.add('cp2clip');
26    elem.appendChild(cp); // pre.appendChild
27    cp.addEventListener('click', async event => {
28      try {
29        const text = event.target.parentElement.textContent;
30        await navigator.clipboard.writeText(text);
31        // event.target.textContent = 'Copied to clipboard'
32        // console.log( "copié >>>" + text + "<<<" );
33        messageBox('cp2clipok', LANG.plugins.copy2clipboard.copied);
34      } catch (err) {
35        console.error('Failed to copy!', err);
36        messageBox('cp2clipnok', LANG.plugins.copy2clipboard.error);
37      }
38    })
39  })
40})
41
42