user7607612
user7607612

Reputation:

How to apply styling on fly when using Highlight.js plugin?

I'm working on some code where I need to trigger event on fly and apply the highlight styling. For some reason the styling is not getting applied.

https://jsfiddle.net/qm9rgh0u/

hljs.initHighlightingOnLoad();

var content_div = document.getElementById("edit");

content_div.addEventListener("keypress", function() {
  hljs.initHighlightingOnLoad();

})
@import url('https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.11.0/styles/default.min.css');
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.11.0/highlight.min.js"></script>

<div id="edit" contenteditable="true">
  <pre>
<code>
    var i = 0,
        colors = ["red","blue","green"];
    var content = document.getElementById("text");
    function appendFunction(e,id){

      var new_span = document.createElement("span");
      new_span.style.color = colors[i];
      new_span.textContent = id.textContent;
      id.append(new_span);
      // var new_span = "<span style=color:'+colors[i]+'>"+id.textContent+"</span>";
      // var
      // id.append(new_span);
    }



      var id = document.getElementById("text");
      id.addEventListener("keyup", function(event){
        appendFunction(event,id);
      })



</code>
</pre>
</div>

Upvotes: 3

Views: 965

Answers (1)

Dalin Huang
Dalin Huang

Reputation: 11342

I added id="codeblock" to your html <code> tag

also with updated js, I changed keypress to blur so you can update the code and when you lose focus you get the updated style:

hljs.initHighlightingOnLoad();

var content_div = document.getElementById("edit");
content_div.addEventListener("blur", function() {
  hljs.highlightBlock(document.getElementById("codeblock"));
})

https://jsfiddle.net/dalinhuang/r2a56w9b/

Upvotes: 2

Related Questions