views:

48

answers:

2

I am using the syntax highlighter plugin and I want to always have it applied to a specific div area. The div's content will change based on a on-click hyperlink. How can I enclose the syntax highlighter script tag around the "mydiv" element at all times?

<script>
    function viewCode() {
        $('#mydiv').load('euler/_48.py');   
    }
</script>

<a href="#" onClick="viewCode();return true">View Code</a>

<div id="mydiv">
    my div's initial content
</div>

<script type="syntaxhighlighter" class="brush: js"><![CDATA[
    //always apply this script to mydiv
]]></script>
A: 

With syntaxHighlighter, you cannot highlight arbitrary elements on the page, so we will stick to the script method instead.

First, give the script and anchor tag an id, like Show Code

Then, use this to load the contents when the user clicks on the link

#show_code.click(function(){
  $.get('euler/_48.py', function(data){
    $('#highlighted').html('<![CDATA[' + data + ']]>');
    SyntaxHighligher.highlight();
  });
});

Remember that the usual method to use syntexhighlighter.js would not work here because the SyntaxHighlighter.all() function only binds the highlight() function to the onload event, so you will have to call that function yourself every time the page updates, by adding a call to the SyntaxHighligher.highlight() function everytime you update the page.


Alternatively, I'd usually recommend the pre method. Its almost the same as above, but we use the pre element instead and use the text() jQuery function to get the escaping done correctly. Using the pre element:

<pre class="brush: js" id="highlighted"></pre>

With this piece of Javascript

$.get('euler/_48.py', function(data){
  $('#highlighted').text(data);
  SyntaxHighligher.highlight();
});
Yi Jiang
Thanks. How would I apply that to #mydiv? Is it just $('#mydiv').get instead of my $('#mydiv').load? I've been trying your suggestion with what I just said but it's not working for me at the moment.
@medikgt You can't, and shouldn't - like I said in the first line, you shouldn't try to use syntaxHighlighter on *any* HTML element - only `script` or `pre`. The `.load()` syntax is special, in that it is actually called from the element.
Yi Jiang
@medikgt I think you are confusing certain things. You need to clarify what you're trying to do here. What I thought you were doing was to load the contents of external files into a `div`, then apply syntax highlighting to it, right?
Yi Jiang
That is correct.
@medikgt Then you need to place the code I gave you into the click event handler, wait while I modify the code.
Yi Jiang
A: 

Hello,

I think you can call HighlightAll method

Example: dp.SyntaxHighlighter.HighlightAll('code');

Sultan

sultan