Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change the theme using highlight.js?

I have the following code:

<head>
    <title></title>
    <link rel="stylesheet" href="./styles/darkula.css">
    <link rel="stylesheet" href="./styles/github.css">
</head>
<body>
    <div class="container">
        <pre>
            <code class="html">
<button class="button is-primary">Primary</button>
            </code>
        </pre>
        <!-- Change theme button -->
        <button onclick="changeTheme()">Change theme</button>
    </div>
    <script src="highlight.pack.js"></script>
    <script>
        hljs.initHighlightingOnLoad();
        document.querySelectorAll("code").forEach(function(element) {
            element.innerHTML = element.innerHTML.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
        });

        function changeTheme() {
            ...
        }
    </script>
</body>

I am loading 2 themes in my file. Because the github theme is being loaded after the darkula theme, it gets applied to all the code elements automatically. This is fine, but I would like to allow users to dynamically change the theme to darkula with the click of the button. I could not find anything in the documentation. How can I do this?

like image 956
darkhorse Avatar asked May 14 '26 14:05

darkhorse


1 Answers

If you are using sass/scss and handle your dependencies with npm, you can do the next thing:

@use "sass:meta";

html[data-theme="light"] {
  @include meta.load-css("highlight.js/styles/a11y-light");
}
html[data-theme="dark"] {
  @include meta.load-css("highlight.js/styles/a11y-dark");
}

To make it to work, you need to define the data-theme attribute in your html tag.

<html data-theme="light">
  <!-- ensure to change it with javascript and define one with default -->
  ...
</html>
like image 50
Lucas Vazquez Avatar answered May 16 '26 05:05

Lucas Vazquez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!