Forum Discussion

Jake_Hembree's avatar
Jake_Hembree
Brass Contributor
Sep 21, 2023
Solved

Using Modern Script Editor web part to copy text from a div container in SharePoint Page

I'm creating a page in SharePoint that will consist of various templates. I don't want to use mailto links because these templates will vary on who they are sent to and I want to person to review the...
  • Jake_Hembree's avatar
    Feb 26, 2024

    Jake_Hembree I figured out the solution!
    For anyone looking to use Script Editor to create a copy to the clipboard button on their SharePoint page, use the following code. Locate the ID of the Div and change the ID on line 31.

    If you're looking to use this button more than once on the same page, remember to change "myFunction" to "myFunction2" and "myFunction3" and so on for additional buttons. Those changes must be made to line 10 and line 31

    The same with "myTooltip" to "myTooltip2" on lines 17 and 32

    I hope this helps anyone looking for a way to do this. :smile:

     

    <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    ​
    </head>
    <body>
    ​
    <script>
    function myFunction(divId) {
      const copyDiv = document.getElementById(divId);
      
      if (copyDiv) {
        const textToCopy = copyDiv.innerText;
        navigator.clipboard.writeText(textToCopy)
          .then(() => {
            let tooltip = document.getElementById("myTooltip");
            tooltip.innerHTML = "Copied"; setInterval( () => {tooltip.innerHTML = "Copy Template"}, 1000);
          })
          .catch(err => {
            console.error('Could not copy text: ', err);
          });
      } else {
        console.error('Element to copy from could not be found');
      }
    }
    </script>
    ​
    ​
    <div>
      <button onclick="myFunction('4fea53bd-80ff-45be-ad02-b29a65423712')" onmouseout="outFunc()">
      <span class="tooltiptext" id="myTooltip">Copy Template</span>
      
    </button>
    </div>
    </body>
    </html>

     

Resources