0

I have a website that I am making that uses the highlight.js script. It's basically a syntax highlighting javascript code that highlights all <code> blocks. I have a <code contenteditable> block. I wanted to make it so that the syntax highlighting is realtime, or in other words, call the higlight function whenever the content is edited. How can I achieve this?

Django HTML:

<link rel="stylesheet" href="{% static 'tokyo-night-dark.min.css' %}">
<div class="main">
<pre><code contenteditable>{{code}}</code></pre>
</div>

Function to execute:

<script>hljs.highlightAll();</script>
2
  • 1
    I highly recommend to read the highlight.js documentation that explains perfectly fine how to use it. Commented Aug 14, 2022 at 7:34
  • I did read it, and I know I have to use the code from the 'Custom Usage' section with an event listener. I guess what I was looking for was how do I get an event from a content editable which I could use, and I just found an answer for that on SO. Commented Aug 14, 2022 at 16:23

1 Answer 1

0

Make sure to add this to your HTML

Link the library, and call highlightAll:

<link rel="stylesheet" href="/path/to/styles/default.min.css">
<script src="/path/to/highlight.min.js"></script>
<script>hljs.highlightAll();</script>

This should automatically highlight code inside of <pre><code> tags

If the above steps didn't work you could do it manually using the class attribute:

<pre><code class="language-html">...</code></pre>
Sign up to request clarification or add additional context in comments.

1 Comment

I read the documentation, all of these lines are present in my code. When I load the page, whatever is default in the code block gets highlighted, but when I edit it it doesn't highlight the new text.

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.