Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clipboard.js not working in Bootstrap modal

I am trying to copy an input value with Clipboard.js: https://clipboardjs.com/. The input is located in a modal:

http://codepen.io/Deka87/pen/eBJOKY

new Clipboard('#copy', {
    text: function(trigger) {
        return $("#copy-input").val();
    }
});

While it works outside of the modal, it fails to work when the input and the copy button are located in a modal window. I tried to init the clipboard function after the modal window is open:

$(".modal").on("shown.bs.modal", function() {
  new Clipboard('#copy', {
      text: function(trigger) {
          return $("#copy-input").val();
      }
  });
});

However, it didn't solve the issue. Any ideas?

like image 385
sdvnksv Avatar asked Nov 10 '16 11:11

sdvnksv


3 Answers

I had the same problem, and I solved this appending the element inside the modal instead of document.body.

function copyToClipboard() {
   const el = document.createElement('textarea');
    el.value = 'text to copy';
    document.getElementById('copy').appendChild(el);
    el.select();
    document.execCommand('Copy');
    document.getElementById('copy').removeChild(el);
}

Bootstrap's modal enforce focus for accessibility (enforceFocus)reasons but that causes problems with lots of third-party libraries

https://github.com/twbs/bootstrap/issues?q=is:issue+enforceFocus+is:closed

like image 157
Thiago Pereira Avatar answered Nov 12 '22 11:11

Thiago Pereira


Try this fork: http://codepen.io/anon/pen/NbxWbQ I forgot to remove the console.log so just ignore that :)

<input type="text" class="form-control" id="copy-input" value="Copied successfully!"/>
    <br />
    <a href="#" id="copy" data-clipboard-target="#copy-input" class="btn btn-default">Copy input content to clipboard</a>

and

$(".modal").on("shown.bs.modal", function() {
  console.log('a', Clipboard, $('#copy'), $("#copy-input").val());
  var clipboard = new Clipboard('#copy')
});
like image 7
marcinrek Avatar answered Nov 12 '22 10:11

marcinrek


You have to set the container

new ClipboardJS('.btn', {
    container: document.getElementById('modal')
});

See this page https://clipboardjs.com/ in the Advanced Usage Section.

like image 7
Erick Eduardo Garcia Avatar answered Nov 12 '22 12:11

Erick Eduardo Garcia