Proper formatting when fetching a code block via URL using Javascript

I am new to Javascript/HTML as of yesterday, and I am attempting to update my website with nicely highlighted code blocks with Prismjs. I have achieved that much, but ran into a problem when attempting to pull the code block from GitHub automatically. The code block is fetched and printed in its entirety, but the first line of the code block is given a large amount of whitespace/tabs when viewed in a browser. I feel as if solving this issue is simple, but I cannot figure it out. I have tried this with multiple files of mine, but all result in extra whitespace in the first line. My HTML script is as follows:

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="http://prismjs.com/themes/prism-okaidia.css" />

    <style>
        .code {
            background-color: #272822;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
            margin: 10px;
            position: relative;
        }

        .copy-button {
            position: absolute;
            top: 10px;
            right: 10px;
            background-color: rgba(169, 169, 169, 0.5);
            border: none;
            border-radius: 5px;
            padding: 5px 10px;
            cursor: pointer;
            opacity: 0.5;
            transition: opacity 0.3s;
        }

        .copy-button:hover {
            opacity: 0.75;
        }

        
    </style>
</head>

<body>
    <div class="code">
        <button class="copy-button" onclick="copyCode()">Copy</button>
        <pre>
            <code class="language-bash" id="code-content">
                <!-- Content will be loaded here -->
            </code>
        </pre>
        <script src="https://prismjs.com/components/prism-core.min.js"></script>
        <script src="https://prismjs.com/plugins/autoloader/prism-autoloader.min.js"></script>
    </div>

    <script>
        function copyCode() {
            const codeElement = document.querySelector('#code-content');
            const codeText = codeElement.textContent;

            // Create a temporary textarea to copy the code text to the clipboard
            const tempTextarea = document.createElement('textarea');
            tempTextarea.value = codeText;
            document.body.appendChild(tempTextarea);
            tempTextarea.select();
            document.execCommand('copy');
            document.body.removeChild(tempTextarea);

            // Change the button text to 'Copied ✓'
            const copyButton = document.querySelector('.copy-button');
            copyButton.textContent="Copied ✓";
        }

        // Fetch code content from the GitHub URL and update the <code> block
        fetch('https://raw.githubusercontent.com/Dillon-McCardell/Bash-Utilities/main/Wifi_Connection_Scripts/connectionStatus.sh')
            .then(response => response.text())
            .then(data => {
                const codeElement = document.querySelector('#code-content');
                codeElement.textContent = data;

                // Initialize Prism highlighting
                Prism.highlightElement(codeElement);
            })
            .catch(error => {
                console.error('Error fetching code content:', error);
            });
        
    </script>
</body>

</html>

This is what I expected for the file (only showing the top):

# A simple bash utility script to return 1 if Internet is available,
# or 0 if it is not. Can be implemented by other scripts.
# Please see connectionStatusHeader.sh for a full featured connection
# script for use within WSL bash files.

But instead I get this:

            # A simple bash utility script to return 1 if Internet is available,
# or 0 if it is not. Can be implemented by other scripts.
# Please see connectionStatusHeader.sh for a full featured connection
# script for use within WSL bash files.

Using a `console.log(data)` statement printed the code block correctly.

I also tried to make the code block into a code snippet but the GUI was not available to me apparently, and attempting to figure out how to do it manually was too painful.

Any help would be appreciated!

  • "I am new to Javascript/HTML as of yesterday" – really? Most folk manage the “Hello World” of HTML by day 2 but you appear to have progressed way beyond that! However – the simple truth of the problem is that you have a pre element that has a nested code element. The space that you are seeing is because the pre element retains the actual spaces used to indent and nest the code element. If you remove the spaces and have simply <pre><code class='language-bash' id="code-content"></code></pre> you should find it is OK

    – 

  • @ProfessorAbronsius Thank you so much! I was hoping it was something so simple. Is there some way I can mark your comment as an answer? Or would you be willing to answer this question directly so I can do so?

    – 

  • Glad I was able to shed light on the problem. Don’t worry about marking as an answer though as I’m not sure it warrants a full answer ~ it’s just one of the idiosyncrasies one gets to know

    – 

Leave a Comment