1

Given this html fragment

<div class="row">
    <div class="col-md-12">
        <pre><code id="sourcecode" class="python">print "Hello World"</code></pre>
    </div>
</div>

I try to change the actual displayed code on the fly, e.g.:

$.ajax({
    type: 'GET',
    url: '/api/1/strategy/source/json/{{ name }}',
    dataType: "json",
    success: function (response) {
        console.log(response);
        $("#sourcecode").textContent = response;
    }
})

Unfortunately it doesn't work. Any hints for me? (in the console log I see the correct response)

Thomas

2
  • 1
    I've no experience with highlight.js, but if you check the docs (highlightjs.org/usage), under "Custom Initialization", it appears you will need to re-run hljs.highlightBlock(block); after editing the #sourcecode element. Commented Nov 16, 2018 at 10:21
  • It highlights print "Hello World"... Commented Nov 16, 2018 at 10:38

1 Answer 1

1

Have a look into the below example, specifically the success function inside your $.ajax function.

As long as the response is valid HTML, the h1js code should be working.


<head>

  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/styles/default.min.css">
  <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/highlight.min.js"></script>

</head>

<body>

  <div class="row">
    <div class="col-md-12">
      <pre><code id="sourcecode" class="python">print "Hello World"</code></pre>
    </div>
  </div>

  <script>
    hljs.initHighlightingOnLoad();

    $(function() {
      $.ajax({
        type: 'GET',
        url: '/api/1/strategy/source/json/{{ name }}',
        dataType: "json",

        success: function (response) {
          console.log(response);
          $("#sourcecode").html(response);
          $('pre code').each(function(i, block) {
            hljs.highlightBlock(block);
          });
        }
      });
    });
  </script>

</body>

Sign up to request clarification or add additional context in comments.

Comments

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.