I will show you how to add a beautiful code box with a Copy button to your Blogger post. This feature is very important for those who write
code-related articles and gives a professional look.
So let's get started—
First go to Blogger Dashboard → Theme → Edit HTML
Now find the </head> tag
Now paste the CSS code given below. This will create the design of the code box and the style of the copy button..code-box {
position: relative;
border: 1px solid #ddd;
border-radius: 5px;
padding: 15px;
overflow: auto;
font-family: 'Courier New', Courier, monospace;
}
/* Copy button */
.copy-button {
position: absolute;
top: 10px;
right: 10px;
background: #007bff;
color: #fff;
border: none;
border-radius: 5px;
padding: 5px 10px;
cursor: pointer;
font-size: 12px;
}
/* Button hover effect */
.copy-button:hover {
background: #0056b3;
}Copy the JS code below and place it above the closing body tag of the Blogger template.
// Add copy button dynamically to each code box
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('.code-box').forEach(function(codeBox) {
const button = document.createElement('button');
button.classList.add('copy-button');
button.innerText = 'Copy';
codeBox.appendChild(button);
button.addEventListener('click', function() {
const code = codeBox.querySelector('code').innerText;
// Copy the code to clipboard
navigator.clipboard.writeText(code).then(() => {
button.innerText = 'Copied!';
setTimeout(() => (button.innerText = 'Copy'), 2000);
}).catch(() => {
button.innerText = 'Failed!';
setTimeout(() => (button.innerText = 'Copy'), 2000);
});
});
codeBox.addEventListener('dblclick', function() {
const code = codeBox.querySelector('code').innerText;
// Copy the code to clipboard
navigator.clipboard.writeText(code).then(() => {
alert('Code copied to clipboard!');
});
});
});
});
Then save.
Use the format below. Using your own format will help you present your website code beautifully to your visitors.
(Must HTML view)
<pre class="code-box">
<code>
Your_Code_Here
</code>
</pre>
You should parse the code you posted.
Click here for Parser.
Place the parsed codes in Your_Code_Here.
Then you publish your page or post.
See your desired work done.
If there is any problem to understand, contact us on Telegram
