Clipboard Utilities
This document explains the functions copyCode
, which are used to copy text and code snippets directly to the clipboard from the user interface. These functions are designed to enhance the user experience by providing instant feedback and are especially useful in environments where quick code snippet copying is needed.
copyCode Function
The copyCode
function is a utility that uses copyToClipboard
to copy text content from a code block located within a specific UI structure. It's tailored for copying code snippets from styled code blocks.
Parameters
- btnElement (
this
): The button element that triggered the copy action. The function finds the nearest code block relative to this button and copies its content. - containerClass (
mockup-code
): The class of the container holding the code block. - initialIconAttr (
{ [key: string]: string }
): An object containing the initial attributes for the icon element. - successIconAttr (
{ [key: string]: string }
): An object containing the attributes to apply to the icon on successful copy. - timeout (
number
): The duration in milliseconds to revert the icon back to the initial state after copying. Default is 2000ms.
Return Value
This function does not return a value. It directly invokes copyToClipboard
to handle the text copying process.
Note: Ensure the button's onclick event is a single line to prevent any issues with the copy action.
onclick="copyCode(this, 'mockup-code', {'textContent': 'Copy'}, {'textContent': 'Copied!'}, 'span')" -> Correct Format
onclick="copyCode( this, 'mockup-code', {'textContent': 'Copy'}, {'textContent': 'Copied!'}, 'span')" -> Incorrect Format
Example Usage Using Image Icon
<div class="mockup-code w-fit relative">
<pre><code>// Example: Copying this snippet
console.log('Hello, world!');</code></pre>
<button onclick="copyCode(this, 'mockup-code', {'src': '/src/app/assets/images/content-copy.svg', 'alt': 'Copy'}, {'src': '/src/app/assets/images/check.svg', 'alt': 'Copied'}, 'img', 2000)"
class="absolute top-0 right-0 p-2 m-2 text-sm bg-blue-500 text-white rounded transition duration-300 cursor-pointer">
<img src="/src/app/assets/images/content-copy.svg" class="size-4" alt="copy code" />
</button>
</div>
Example Usage Using Span Content
<div class="mockup-code w-fit relative">
<pre><code>// Example with text button ddd
console.log('Button with text icon');</code></pre>
<button
onclick="copyCode(this, 'mockup-code', {'textContent': 'Copy'}, {'textContent': 'Copied!'}, 'span')"
class="absolute top-0 right-0 p-2 m-2 text-sm bg-green-500 text-white rounded transition duration-300 cursor-pointer">
<span>Copy</span>
</button>
</div>