ccampbell / rainbow

Simple syntax highlighting library written in javascript
http://rainbowco.de
Apache License 2.0
3.3k stars 465 forks source link

How to retrigger rainbow for dynamic code #262

Closed mkfizi closed 1 year ago

mkfizi commented 1 year ago

I have html code below combined with Alpinejs

<pre><code class="text-sm" data-language="html"
    x-data="{ 
        code: '&lt;p&gt;Start&lt;p&gt;' 
    }"
    x-text="code"
    x-init="
        setTimeout(() => {
            code = '&lt;div&gt;Changed&lt;/div&gt;'
        }, 1000)
    "
></code></pre>

After 1 second the output doesnt follow rainbow format anymore. How to retrigger rainbow for when the content is changed?

mkfizi commented 1 year ago

Resolved by wrapping entire element in div then redraw elements using div as below

<div
    x-data: {
        code: '&lt;p&gt;Changed&lt;p&gt;' 
    }
    x-init="
        setTimeout(() => {
            div = document.createElement('div');
            div.innerHTML = `<pre><code data-language=&quot;html&quot;>${code}</code></pre>`
            Rainbow.color(div, function() {
                $el.innerHTML = '';
                $el.appendChild(div)
            });
        }, 1000)
    "
>
    <pre><code class="text-sm" data-language="html">&lt;p&gt;Start&lt;p&gt;</code></pre>
</div>