📁

Creating Beautiful Code Blocks with Copy Code Button using Prism.js

 

Create Code Box with with copy button using Prism Js

 

Are you looking to make your code snippets more appealing and user-friendly on your website?

In the world of web development, it is essential to present code snippets in an organized and visually appealing way.

One popular tool for achieving this is Prism.js,  In this comprehensive tutorial,  you would be guided through the process of creating stylish code blocks (box)  with a handy “Copy” button using Prism.js.

Prism.js➚ is a versatile and lightweight syntax highlighter that makes code formatting beautification a breeze.

I also love going for  providing a seamless user experience, and a “Copy Code” button alongside the code block should not be a miss feature to have on your site.

This button would allow users to quickly and easily copy any code you provided without having to manually select and copy the text, and making it easier for users to interact with and utilize your code snippets.

Lets move into how to integrate this on your site. This code is applicable to any blogging platform and Content Managing System (CMS) that accepts HTML Editing.

If you use Blogger, WordPress etc make sure you are on HTML Edit View.

 

Step 1: Setting Up the HTML Structure

Let’s start by creating an HTML file and setting up the necessary foundation. We’ll include the essential stylesheets and scripts required for Prism.js and our copy code button functionality.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Code Box with Prism.js</title>
  
  <!-- Prism.js CSS - Choose your theme from https://prismjs.com/ -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.min.css" rel="stylesheet">
  
  <!-- Font Awesome for icons (optional) -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  
  <style>
    /* Code block styles */
    pre {
      position: relative;
      padding: 1em;
      background-color: #f5f2f0;
      border: 1px solid #ddd;
      border-radius: 4px;
      overflow: auto;
    }

    code {
      font-family: "Courier New", Consolas, monospace;
    }

    /* Copy code button styles */
    .copy-code-button {
      position: absolute;
      top: 0.5em;
      right: 0.5em;
      padding: 0.5em 1em;
      font-size: 14px;
      background-color: #333;
      color: #fff;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s;
    }
    
    .copy-code-button:hover {
      background-color: #555;
    }
  </style>
</head>
<body>

 

Step 2: Creating the Code Block and Copy Code Button

Inside the <body> tag, let’s build our code block and add the copy code button for a seamless user experience. We’ll enclose our code within the <code> element with the appropriate language class, which is wrapped by the <pre> tag.

<pre><code class="language-javascript">function greet() {
  console.log("Hello, Sdavidprince Here!");
}
</code></pre>
<button class="copy-code-button">Copy</button>

 

Important Notes:

  • The class="language-javascript" tells Prism.js which language syntax to use. You can change this to language-html, language-css, language-python, etc. Check the supported languages on the official Prism.js site.
  • The copy button should be placed right after the closing </pre> tag, not inside it.

 

Icon Option

You can replace the copy button text with a copy icon instead. For this we are going to use Font-Awesome. You can use SVG or any other external icon library.

To add Font Awesome icon, replace <button class="copy-code-button">Copy</button> with:

<button class="copy-code-button"><i class="fas fa-copy"></i></button>

 

You can check your preferred icon from Font Awesome Icons ➚, just replace “fas fa-copy” with your preferred icon class.

Step 3: Incorporating Prism.js and Copy Code Button Functionality

To make our code block syntax-highlighted, we’ll include the Prism.js library and add a script to manage the copy code button’s functionality. Add these scripts before the closing </body> tag:

<script>
  // Add click event listener to each copy code button
  document.querySelectorAll(".copy-code-button").forEach(function(button) {
    button.addEventListener("click", function() {
      // Get the code element (previous sibling of the button)
      var preElement = this.previousElementSibling;
      var codeElement = preElement.querySelector('code') || preElement;
    
      // Create a temporary textarea to copy the code
      var textarea = document.createElement("textarea");
      textarea.value = codeElement.textContent;
      document.body.appendChild(textarea);

      // Select and copy the code
      textarea.select();
      document.execCommand("copy");

      // Remove the temporary textarea
      document.body.removeChild(textarea);

      // Change the button text to "Copied!" for a short duration
      var originalHTML = this.innerHTML;
      this.innerHTML = "Copied!";
      setTimeout(function() {
        button.innerHTML = originalHTML;
      }, 1500);
    });
  });
</script>

<!-- Prism.js Core Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>

<!-- Add language components as needed -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-javascript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-css.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-markup.min.js"></script>

</body>
</html>

Script Loading Note:

Make sure to load the language-specific Prism.js components for the languages you’re using. You can find all available language components on the Prism.js website. Alternatively, you can use the Prism.js download page to create a custom build with only the languages and features you need.

Complete Working Example

Here’s a complete working example putting it all together:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Code Box with Prism.js</title>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    pre {
      position: relative;
      padding: 1em;
      background-color: #f5f2f0;
      border: 1px solid #ddd;
      border-radius: 4px;
      overflow: auto;
    }
    code {
      font-family: "Courier New", Consolas, monospace;
    }
    .copy-code-button {
      position: absolute;
      top: 0.5em;
      right: 0.5em;
      padding: 0.5em 1em;
      font-size: 14px;
      background-color: #333;
      color: #fff;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s;
    }
    .copy-code-button:hover {
      background-color: #555;
    }
  </style>
</head>
<body>

<h1>My Code Example</h1>

<pre><code class="language-javascript">function greet() {
  console.log("Hello, Sdavidprince Here!");
}

greet();
</code></pre>
<button class="copy-code-button"><i class="fas fa-copy"></i></button>

<script>
  document.querySelectorAll(".copy-code-button").forEach(function(button) {
    button.addEventListener("click", function() {
      var preElement = this.previousElementSibling;
      var codeElement = preElement.querySelector('code') || preElement;
      var textarea = document.createElement("textarea");
      textarea.value = codeElement.textContent;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand("copy");
      document.body.removeChild(textarea);
      var originalHTML = this.innerHTML;
      this.innerHTML = "Copied!";
      setTimeout(function() {
        button.innerHTML = originalHTML;
      }, 1500);
    });
  });
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-javascript.min.js"></script>

</body>
</html>

 

Step 4: Testing and Customization

Save your HTML file and open it in your web browser. You’ll now see a beautifully styled code block with a “Copy” button. Clicking the button will copy the code to your clipboard, and the button text will momentarily change to “Copied!” to provide user feedback.

 

Customization:

Feel free to customize the code block styles and button styles to match your website’s design. You can also explore different Prism.js themes from the official themes page to alter the code block’s appearance according to your preferences. Popular themes include:

  • prism-okaidia.css (dark theme)
  • prism-twilight.css (dark theme)
  • prism-tomorrow.css (clean theme)
  • prism-solarizedlight.css (light theme)

You can also use the Prism.js download builder to create a custom package with your preferred theme, languages, and plugins.

 

Conclusion

This post shared the process of creating attractive code blocks with a convenient “Copy” button using Prism.js. This not only enhances the readability of code snippets on any website but also offers users an effortless way to copy code examples. Anyone can Experiment with various styles and themes to seamlessly integrate this feature into their web project. Happy coding!

 

Fediverse reactions

Related – According to the Not Algorithm

8 responses

  1. Basit

    Ok Thanks i swicthed to Prism. It is a little more lighter and the best alternative to highlight js.
    And i think this post needs updating and there is an extra js to add. Prisim even
    has a more simple implementation like higlight.js. Note use mist use code tag and add language if you are not sure use lang-css
    eg
    <pre>&lt;code class=&quot;language-css&quot;&lt;p { color: red }</code></pre>

    p { color: red }

    for inline code snippets use

    <code class="language-css">p { color: red }</code>.

    1. S David Prince

      Thank you
      The post would be updated

  2. Tech Master Nedu
    Tech Master Nedu

    I would have loved this code but the copy on the copy button is always being copied too along with the rest of the code and it’s not friendly having to be whatching out and deleting those. It ruined my template thank Goodness I observed and notice it was the copy button fault

    1. sdavidprince

      Yea thanks 🤧 I’ve updated it to include an Icon option and I use font awesome and the problem is fixed that way. The code is safe to use.

  3. Abraham

    What if I want the copy button to be icon instead of text

    1. sdavidprince

      there is an Icon option now and it makes the whole code more neat.

      1. Newcommer

        I want the syntax highlighter. Right Prism is Lightweight?.. because my blog is full of pligins and gadgets already and I score 45 in page speed insight alreadand I’m optimizing and avoiding heavy scripts

        1. sdavidprince

          Prism is lightweight. Its just 2kb

Leave a Reply

Your email address will not be published. Required fields are marked *

Your post must include a link to this post.

How does this work?
This Site accepts webmentions and pings
v

This site is undergoing another major reconstruction