How to dynamically change the theme using highlight.js?

7.5k Views Asked by At

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?

2

There are 2 best solutions below

0
Lenny D On

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/demo/

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

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

0
Lucas Vazquez On

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>