JSFiddle - React, Tailwind, and code Playground
by dsmith33
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Testing HighlightJS</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/styles/routeros.min.css">
</head>
<body>
<h3>Testing HighlightJS Multiple blocks</h3>
<h4>First Code block</h4>
<pre><code class="language-css">
.class{
font-size: 0.85rem;
font-weight: 600;
font-family: monospace;
}
h1 .header{
font-size: 1.5rem;;
font-family: Arial;
}
</code></pre>
<h4>Second Code block</h4>
<pre><code class="language-css">
.class{
font-size: 0.85rem;
font-weight: 600;
font-family: monospace;
}
h1 .header{
font-size: 1.5rem;;
font-family: Arial;
}
</code></pre>
<h4>Third Code block</h4>
<pre><code class="language-css">
.class{
font-size: 0.85rem;
font-weight: 600;
font-family: monospace;
}
h1 .header{
font-size: 1.5rem;;
font-family: Arial;
}
</code></pre>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/languages/css.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/2.6.0/highlightjs-line-numbers.min.js"></script>
<script>hljs.highlightAll(); hljs.initLineNumbersOnLoad();</script>
</body>
</html>
CSS
span > button.btnCopy {
position: absolute;
right: 0;
margin-top: 0.6rem;
}
pre {
position: relative;
}
.btnCopy{border:none; background-color: #e8e8e8;}
/*background-color:a5a5a5, 9c9c9c*/
.btnCopy:hover{background-color: #585858}
JavaScript
window.addEventListener('load', function() {
var y = document.querySelectorAll("pre code");
for(var i = 0; i < y.length; i++) {
y[i].innerHTML = y[i].innerHTML.replace(/^\r?\n/, "");
}
const textspan = document.createElement("SPAN");
const bgbutton = document.createElement("BUTTON");
bgbutton.classList.add("btnCopy", "badge");
bgbutton.innerText = "copy";
bgbutton.addEventListener('click', copytextHandle);
textspan.appendChild(bgbutton);
const codeSyn = document.querySelectorAll("pre");
codeSyn.forEach(function(el) {
el.insertAdjacentElement('afterbegin', textspan);
})
})
const copytextHandle = (e) => {
const codeBlock = document.querySelectorAll(".hljs-ln")[e.target.dataset.idx];
const text = codeBlock
.innerText
.trim()
.replace(/\s+/g, " ")
.replace(/}/g, "}\n")
.replace(/{ /g, "{\n ")
.replace(/;/g, ";\n ")
copySuccess.classList.remove('hide');
navigator.clipboard.writeText(text).then(() => setTimeout(() => bgbutton.innerHTML("Copied"),200),
(e) => {
console.log('Error writing to the clipboard', e.message);
copySuccess.classList.add('hide');
}
);
};