Posts

How to Create a Colored Syntax Highlighter with the Copy Code Function in Blogger

 Syntax Highlighter Blogger

Syntax highlighter is a feature of several text editors that is able to display source code in various colors to make it easier for users to sort written code.

In a web page, Syntax highlighter is usually found on a web that discusses programming code, as in this blog, even in this article I use the syntax highlighter to embed code in posts.

In this article, I will share how to create a colored highlighter syntax in blogger with the additional copy code feature which will certainly be of great help to blog visitors.

With the copy code feature, visitors will easily copy existing code in just one click. How to make?

How to Install Syntax Highlighter on Blogger

Before you follow these steps, check first whether the CSS code .post-body preor .post-body pre codealready in the blog template that you use? if so, delete them first so there is no clash.

Next, add the following line of CSS code just below the code <style>.

css
/* syntax highlighter */ .post-body pre{position:relative;width:100%;background-color:#262a2d;border-radius:4px;margin:25px auto;-moz-tab-size:2;-o-tab-size:2;tab-size:2;word-break:normal;user-select:text;-webkit-user-select:text;-khtml-user-select:text;-moz-user-select:text;-ms-user-select:text;user-select:text;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none} .post-body pre code{color:rgba(255,255,255,.9);display:block;padding:20px;white-space:pre;font-family:monospace;font-size:14px;overflow-x:auto;line-height:1.5em} .hljs,.hljs-subst,.hljs-tag{color:#eaebec} .hljs-emphasis,.hljs-strong{color:#a8a8a2} .hljs-bullet,.hljs-link,.hljs-literal,.hljs-number,.hljs-quote,.hljs-regexp{color:#ae81ff} .hljs-code,.hljs-section,.hljs-selector-class,.hljs-title{color:#a6e22e} .hljs-strong{font-weight:700} .hljs-emphasis{font-style:italic} .hljs-attr,.hljs-keyword,.hljs-name,.hljs-selector-tag{color:#f15a5a} .hljs-attribute,.hljs-symbol{color:#66d9ef} .hljs-class .hljs-title,.hljs-params{color:#f8f8f2} .hljs-addition,.hljs-built_in,.hljs-builtin-name,.hljs-selector-attr,.hljs-selector-id,.hljs-selector-pseudo,.hljs-string,.hljs-template-variable,.hljs-type,.hljs-variable{color:#e6db74} .hljs-comment,.hljs-deletion,.hljs-meta{color:#75715e} .code-badge-copy-icon{background:url("data:image/svg+xml,%3Csvg viewBox='0 0 512 512' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M391.89,450H163a50.17,50.17,0,0,1-50.11-50.11V98.11A50.17,50.17,0,0,1,163,48h150.1a15,15,0,0,1,10.61,4.39L437.61,166.27A15,15,0,0,1,442,176.88v223A50.17,50.17,0,0,1,391.89,450ZM163,78a20.13,20.13,0,0,0-20.11,20.11V399.89A20.13,20.13,0,0,0,163,420H391.89A20.13,20.13,0,0,0,412,399.89V183.09L306.91,78Z' fill='%23c6c9ce'/%3E%3Cpath d='M427,191.88H348.23a50.17,50.17,0,0,1-50.11-50.11V63a15,15,0,0,1,30,0v78.77a20.13,20.13,0,0,0,20.11,20.11H427a15,15,0,0,1,0,30Z' fill='%23c6c9ce'/%3E%3C/svg%3E");background-size:55% 55%;background-repeat:no-repeat;background-position:center;cursor:pointer;padding:7px 15px;margin:-5px -8px -5px -14px} .code-badge > .code-badge-check-icon{background:green} .code-badge-check-icon{cursor:pointer;padding:0 7px;margin:-5px 0 -5px -5px;background:url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGFyaWEtaGlkZGVuPSJ0cnVlIiBmb2N1c2FibGU9ImZhbHNlIiBkYXRhLXByZWZpeD0iZmFzIiBkYXRhLWljb249ImNoZWNrIiBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtY2hlY2sgZmEtdy0xNiIgcm9sZT0iaW1nIiB2aWV3Qm94PSIwIDAgNTEyIDUxMiIgc3R5bGU9IiYjMTA7ICAgIGNvbG9yOiAjMmFmZjMyOyYjMTA7Ij48cGF0aCBmaWxsPSJjdXJyZW50Q29sb3IiIGQ9Ik0xNzMuODk4IDQzOS40MDRsLTE2Ni40LTE2Ni40Yy05Ljk5Ny05Ljk5Ny05Ljk5Ny0yNi4yMDYgMC0zNi4yMDRsMzYuMjAzLTM2LjIwNGM5Ljk5Ny05Ljk5OCAyNi4yMDctOS45OTggMzYuMjA0IDBMMTkyIDMxMi42OSA0MzIuMDk1IDcyLjU5NmM5Ljk5Ny05Ljk5NyAyNi4yMDctOS45OTcgMzYuMjA0IDBsMzYuMjAzIDM2LjIwNGM5Ljk5NyA5Ljk5NyA5Ljk5NyAyNi4yMDYgMCAzNi4yMDRsLTI5NC40IDI5NC40MDFjLTkuOTk4IDkuOTk3LTI2LjIwNyA5Ljk5Ny0zNi4yMDQtLjAwMXoiLz48L3N2Zz4=');background-size:100% 100%} #copyy i.code-badge-copy-icon:before{content:'Copy Code';font-style:normal;position:absolute;display:block;top:-20px;width:max-content;background:rgba(0,0,0,.57);color:#fff;border-radius:3px;right:0;padding:2px 6px;visibility:hidden;opacity:0;transition:all .2s ease} #copyy:hover i.code-badge-copy-icon::before{visibility:visible;opacity:1;top:-33px} #copyy i.code-badge-copy-icon:after{content:'';position:absolute;top:0;right:13px;border-left:solid transparent 4px;border-right:solid transparent 4px;border-top:solid rgba(0,0,0,.57) 4px;opacity:0;visibility:hidden;transition:all .2s ease} #copyy:hover i.code-badge-copy-icon::after{visibility:visible;opacity:1;top:-9.8px} #copyy i.code-badge-check-icon:before{content:'Code Copied!';font-style:normal;position:absolute;display:block;top:-33px;width:max-content;background:rgba(0,0,0,.57);color:#fff;border-radius:3px;right:0;padding:2px 6px;transition:all .2s ease} #copyy i.code-badge-check-icon:after{content:'';position:absolute;top:-9.8px;right:13px;border-left:solid transparent 4px;border-right:solid transparent 4px;border-top:solid rgba(0,0,0,.57) 4px;transition:all .2s ease}

Because the highlighter syntax created this time has a color sorter and copy code feature, here I am adding javascript to perform its function.

I use a color feature that is already available on Github, namely highlight.js version 10.4.0 which is the latest update.

While the copy code feature I use a script that is also available on Github, namely highlightjs-badge.js version 0.1.9 which is also the latest update.

Then still on the theme edit page, look for the code </body>and then place the following javascript code right above it.

javascript
<b:if cond='data:view.isPost'> <script> //<![CDATA[ /* highlight.js badge */ "use strict";!function(e,o){"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?o(e):function(e){if(!e.document)throw new Error("A window with a document is required");return o(e)}:o(e)}("undefined"!=typeof window?window:this,function(y,e){var o;function t(e){var m={templateSelector:"#CodeBadgeTemplate",contentSelector:"body",loadDelay:0,copyIconClass:"fa fa-copy",copyIconContent:"",checkIconClass:"fa fa-check text-success",checkIconContent:"",onBeforeCodeCopied:null};function o(){m.loadDelay?setTimeout(t,loadDelay):t()}function t(){var e,o,t;document.querySelector(m.templateSelector)||((e=document.createElement("div")).innerHTML=function(){for(var e=["<style>","@media print {","  .code-badge { display: none; }","}"," .dark-mode .code-badge {","        background: rgba(78,95,109,.10);","    }"," .code-badge-pre {","        position: relative;","    }","    .code-badge {","        display: flex;","        flex-direction: row;","        white-space: normal;","        background: rgba(88,101,111,.63);","        color: #333;","        font-size: 13px;","        line-height: 1.5em;","        opacity: 0.5;","        transition: opacity linear 0.5s;","        border-radius: 0 4px 0 4px;","        padding: 5px 8px 5px 8px;","        position: absolute;","        right: 0;","        top: 0;","    }","    .code-badge.active {","        opacity: 0.8;","    }","","    .code-badge:hover {","        opacity: .95;","    }","","    .code-badge a,","    .code-badge a:hover {","        text-decoration: none;","    }","","    .code-badge-language {","        margin-right: 10px;","        font-weight: 600;","        color: goldenrod;","    }","    .fa.text-success:{ color: limegreen !important }","</style>",'<div id="CodeBadgeTemplate" style="display:none">','    <div class="code-badge">','        <div class="code-badge-language" >{{language}}</div>','        <div  id="copyy" title="Salin Code">','            <i class="{{copyIconClass}}"></i></i></a>',"        </div>","    </div>","</div>"],o="",t=0;t<e.length;t++)o+=e[t]+"\n";return o}(),o=e.querySelector("style"),t=e.querySelector(m.templateSelector),document.body.appendChild(o),document.body.appendChild(t));for(var n=document.querySelector(m.templateSelector).innerHTML,c=document.querySelectorAll("pre>code.hljs"),a=0;a<c.length;a++){var r=c[a];if(!r.querySelector(".code-badge")){for(var d="",l=0;l<r.classList.length;l++){var i=r.classList[l];if("language-"===i.substr(0,9)){d=r.classList[l].replace("language-","");break}if("lang-"===i.substr(0,5)){d=r.classList[l].replace("lang-","");break}if(!d)for(var s=0;s<r.classList.length;s++)if("hljs"!=r.classList[s]){d=r.classList[s];break}}"ps"==(d=d?d.toLowerCase():"text")?d="powershell":"cs"==d?d="csharp":"js"==d?d="javascript":"ts"==d?d="typescript":"fox"==d&&(d="foxpro");var p=n.replace("{{language}}",d).replace("{{copyIconClass}}",m.copyIconClass).trim(),u=document.createElement("div");u.innerHTML=p,u=u.querySelector(".code-badge");var g=r.parentElement;g.classList.add("code-badge-pre"),m.copyIconContent&&(u.querySelector(".code-badge-copy-icon").innerText=m.copyIconContent),g.insertBefore(u,r)}}document.querySelector(m.contentSelector).addEventListener("click",function(c){return c.srcElement.classList.contains("code-badge-copy-icon")&&(c.preventDefault(),c.cancelBubble=!0,function(){var e=c.srcElement.parentElement.parentElement.parentElement,o=e.querySelector("pre>code"),t=o.textContent||o.innerText;m.onBeforeCodeCopied&&(t=m.onBeforeCodeCopied(t,o));var n=document.createElement("textarea");n.value=t.trim(),document.body.appendChild(n),n.style.display="block",y.document.documentMode?n.setSelectionRange(0,n.value.length):n.select(),document.execCommand("copy"),document.body.removeChild(n),function(e){var o=m.copyIconClass.split(" "),t=m.checkIconClass.split(" "),n=e.querySelector(".code-badge-copy-icon");n.innerText=m.checkIconContent;for(var c=0;c<o.length;c++)n.classList.remove(o[c]);for(c=0;c<t.length;c++)n.classList.add(t[c]);setTimeout(function(){n.innerText=m.copyIconContent;for(var e=0;e<t.length;e++)n.classList.remove(t[e]);for(e=0;e<o.length;e++)n.classList.add(o[e])},2e3)}(e)}()),!1})}Object.assign(m,e),"loading"==document.readyState?document.addEventListener("DOMContentLoaded",o):o()}"boolean"!=typeof o&&(o=!1),y.highlightJsBadge=t,y.module&&y.module.exports&&(y.module.exports.highlightJsBadge=t),o&&t()}); /* Highlight.js */ document.addEventListener("DOMContentLoaded", (event) => {   var pres = document.querySelectorAll("pre>code");   for (var i = 0; i < pres.length; i++) {     hljs.highlightBlock(pres[i]);   }   var options = {     contentSelector: ".post-body",     loadDelay:0,     copyIconClass: "code-badge-copy-icon",     checkIconClass: "code-badge-check-icon",     onBeforeTextCopied: function(text, codeElement) {       return text;      }   };   window.highlightJsBadge(options); }); function downloadJSAtOnloadz(){var e=document.createElement("script");e.src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.4.0/highlight.min.js",document.body.appendChild(e)}window.addEventListener?window.addEventListener("load",downloadJSAtOnloadz,!1):window.attachEvent?window.attachEvent("onload",downloadJSAtOnloadz):window.onload=downloadJSAtOnloadz; //]]> </script> <script src='https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.4.0/highlight.min.js'/> </b:if>

At this point, the color highlighter syntax with the copy code feature is already installed and can be used.

How to Use Syntax Highlighter on Blogger

To use the highlighter syntax in blogger posts, just call it using the code <pre><code class="jenis_code">.

An example can be seen below.

If you want to display HTML code, the format is like this.


html
<pre><code class="html"> <!-- Masukkan kode HTML di sini --> </code></pre>

If you want to display CSS code, the format is like this.

html
<pre><code class="css"> <!-- Masukkan kode CSS di sini --> </code></pre>

If you want to display Javascript code, the format is like this.

html
<pre><code class="js"> <!-- Masukkan kode Javascript di sini --> </code></pre>

and If you want to display several types of code at once, such as html, javascript, and css, the format is like this.

html
<pre><code class="html js css"> <!-- Masukkan kode html, javascript, dan css di sini --> </code></pre>

You only need to separate the type of code with spaces, or if you don't want to be complicated, you don't need to add a class, it doesn't matter because it will automatically read the type of code that appears.

Warning !
Before entering the code into the blogger editor, the code must be parsed so as not to damage the appearance of the template.

To parse code, visit this page. Parse Code .

There are many types of highlighter syntax scripts, and they are easy to find on the internet, especially on github. For example prism.js, rainbow.js, and many others.

I chose highlight.js because it's easy to use. You can experiment yourself using other javascript to see a different look.

Rate This Article

Thanks for reading: How to Create a Colored Syntax Highlighter with the Copy Code Function in Blogger, Stay tune to get latest Blogging Tips.

Getting Info...

Post a Comment

Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.