20

My website is generating some content dynamically, so I have to somehow launch the highlight.js plugin again after loading it.

This code is used to launch the highlighter:

hljs.initHighlightingOnLoad();

I tried to do something like hljs.initHighlighting(); to do this again but it does not work.

boreq
  • 791
  • 2
  • 10
  • 18
  • Are you using Turbolinks? Because if you are, I'm pretty sure that's the delimiter. I can't get the two to work together (something to do with the hljs's asynchronousity). Turbolinks is infamous for causing problems and complications. – JackHasaKeyboard Dec 13 '17 at 22:49

3 Answers3

47

You must set called to false first:

hljs.initHighlighting.called = false;
hljs.initHighlighting();
Serhii Polishchuk
  • 1,442
  • 17
  • 22
6

You can reinitialize all of the codeblocks like this.

$(document).ready(function() {
   $('pre code').each(function(i, e) {hljs.highlightBlock(e)});
});

or if you have a div with an ID of myBlock, you can do this.

$(document).ready(function() {
   $('#myBlock').each(function(i, e) {hljs.highlightBlock(e)});
});
planetoftheweb
  • 222
  • 4
  • 10
  • Does Sergey's answer not apply it for all the blocks? – ahnbizcad Feb 20 '15 at 01:31
  • 1
    Also there's no reason to believe the questioner is using jQuery, unless I'm missing something? – Tommy Nov 29 '17 at 21:31
  • 1
    Thank you for your answer! I use this in my react application to update the components when the state is changed. it can be called in componentDidUpdate() with the follow code. var blocks = document.querySelectorAll('pre code:not(.hljs)'); Array.prototype.forEach.call(blocks, hljs.highlightBlock); – luvwinnie Jan 28 '19 at 09:07
0

i hope this could solve your problem.. you have to use

hljs.highlightAll()

since, hljs.initHighlightingOnLoad() is deprecated since version 10.6.

if you're using react, you could apply at componentdidMount..

  useEffect(() => {
    hljs.highlightAll()
  }, []);

or, if another framework, please call that function when page loaded. more: https://highlightjs.readthedocs.io/en/latest/api.html

Handi
  • 59
  • 5