1

I'm using the highlight.js library to display code snippets on my webpage. I'd like to add a button that allows users to switch between light and dark themes for the code snippets. Ideally, clicking the button should dynamically change the CSS theme file linked to highlight.js, transitioning the code snippet's appearance from light to dark or vice versa.

I've implemented the following code using JavaScript to achieve this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>highlight.js</title>
    <link rel="stylesheet" id="theme-link" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/go.min.js"></script>
    <script>
        hljs.highlightAll();

        var currentTheme = "light";
        function toggleTheme() {
            var themeLink = document.getElementById("theme-link");
            if(currentTheme === "light"){
                themeLink.href = "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/tomorrow-night-blue.css";
                currentTheme = "dark";
            } else {
                themeLink.href = "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css";
                currentTheme = "light";
            }
        };
    </script>
</head>
<body>
    <pre>
        <code class="language-python">
            print("Hello World!");
        </code>
    </pre>
    
    <pre>
        <code class="language-python">
            print("Hello World!");
        </code>
    </pre>
    <button onclick="toggleTheme()">Toggle theme</button>
</body>
</html>

This code seems to work, but Are there any alternative or more efficient ways to achieve the same functionality?

I'd appreciate any insights or suggestions from the community!

2

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.