How to add a stylish responsive code box in blogger post clipboard copy button
In this post of Blogger coding tips, you learn how to create a code box for a blogger blogspot post clipboard that prevents visitors from copying code by using HTML, CSS, and JavaScript.
![]() |
How to add a responsive code box in the blogger post clipboard copy button |
1. Create HTML of blogger code box:
Open the HTML view for your Blogger post and create the structure for your code box. Include a <pre> tag for the code and a button for copying.
<div class="code-box">
<pre class="code">
<!-- Your code goes here -->
</pre>
<button class="copy-button" onclick="copyCode()">Copy Code</button>
</div>
2. Code box Style with CSS:
Add some styles to make your code box responsive and visually appealing. You can place the following styles in your post's CSS section or use inline styles within the HTML.
CSS code box code:
.code-box {position: relative;overflow: hidden;border: 1px solid #ddd;border-radius: 5px;margin: 15px 0;}.code {margin: 0;padding: 15px;white-space: pre-wrap;}.copy-button {position: absolute;top: 5px;right: 5px;padding: 5px 10px;background-color: #4CAF50;color: #fff;border: none;border-radius: 3px;cursor: pointer;}
3. Add JavaScript for code box Copying:
Include a small JavaScript function to handle the copy-to-clipboard functionality.
function copyCode() {var codeElement = document.querySelector('.code');var range = document.createRange();range.selectNode(codeElement);window.getSelection().removeAllRanges();window.getSelection().addRange(range);document.execCommand('copy');window.getSelection().removeAllRanges();// Change button text temporarilyvar copyButton = document.querySelector('.copy-button');copyButton.innerText = 'Copied!';setTimeout(function () {copyButton.innerText = 'Copy Code';}, 1500);}
Add Required JavaScript Libraries:
Include the necessary JavaScript libraries for clipboard copy. Add the following script tag just before the closing </body> tag in your post.
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script><script>new ClipboardJS('.copy-button', {target: function(trigger) {return trigger.previousElementSibling;}});</script>
This script uses the Clipboard.js library for handling clipboard operations.
Save and Preview:
Save your changes and preview your Blogger post to see the responsive code box with a copy-to-clipboard button.
Remember to replace the placeholder code in the <pre> tag with your actual code. Additionally, make sure to adjust styles and layout according to your blog's theme.
Example output:
COPY YOUR CODE FROM HERE
Comments :
Post a Comment