6

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?

darkhorse
  • 8,192
  • 21
  • 72
  • 148

2 Answers2

6

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>
Lucas Vazquez
  • 1,456
  • 16
  • 20
4

There's a github response to this same question here https://github.com/highlightjs/highlight.js/issues/2115

Basically you include all the themes you want, and then disable all the link tags except for the selected theme.

The highlight.js demo page does this https://highlightjs.org/static/demo/

The GitHub repository is for the code can be found here.

(https://github.com/highlightjs/highlight.js/blob/master/demo/demo.js)

Lenny D
  • 1,734
  • 4
  • 22
  • 43