Search code examples
javascriptjqueryjekyll

Copy highlighted code into clipboard in jekyll


I am creating a blog using jekyll. I am using prettyprint to highlight the code snippets. I have written a jquery to display a button on hover of the code snippet (inside <pre> tag). On the button click I am getting the entire html of the code snippet but I want to copy the pure text of the code snippet.

Can someone please advise me how to achieve this?


Solution

  • The document.execCommand function can be used to copy text to the clipboard in JavaScript. jQuery is not required.

    function copy() {
      var element = document.getElementById('input');
    
      element.select();
      document.execCommand('copy');
      element.blur();
    }
    <input id="input" />
    <button onclick="copy()">Copy Text</button>