Create Beautiful Code Blocks with Copy Code Button using Prism.js - SDavidPrince Space

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

Create 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 your you are on HTML Edit View.{alertSuccess}


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">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/themes/prism.css" rel="stylesheet">
  <style>
    /* Code block styles */
    pre {
      position: relative;
      padding: 1em;
      background-color: #f0f0f0;
      border: 1px solid #ddd;
      border-radius: 4px;
    }

    code {
      display: block;
      font-family: "Courier New", 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;
    }
  </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 <pre> element, which is in turn wrapped by the <code> tag.

<pre>
  function greet() {
    console.log("Hello, Sdavidprince Here!");
  }

  <button class="copy-code-button">Copy</button>
</pre>


Icon Option

You can replace the copy button text to 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, Replace "<button class="copy-code-button">Copy</button>"
 with
<button class="copy-code-button"><span><i class="fas fa-copy"> </i></span></button>

You can check your preferred Icon from Font Awesome ➚, just replace "fa 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.

<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
      var codeElement = this.parentElement;
    
      // Create a temporary textarea to copy the code
      var textarea = document.createElement("textarea");
      textarea.value = codeElement.innerText;
      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 originalText = this.innerText;
      this.innerText = "Copied!";
      setTimeout(function() {
        button.innerText = originalText;
      }, 1500);
    });
  });
</script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/prism/1.27.0/prism.min.js'/>


Update Note:

If you use Icon for the copy button you can as well update the teal highlighted code to the one below

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


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 to alter the code block's appearance according to your preferences.


Conclusion

In this tutorial, we've walked you through 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 your website but also offers users an effortless way to copy code examples. Experiment with various styles and themes to seamlessly integrate this feature into your web project. Happy coding!


Please write your comments