3

Disclaimer: I know this type of question has been asked here before, I just can't seem to find it. I have tried searching for a bunch of different $.ajax dynamic + live() type stuff but can't find the solution, anyway, here is the problem.

Problem:

I am building a site where I can save my pieces of code. I am having the content pulled from a database via $.ajax. Here is the website: InsanelyWeb.com the select box options content is also dynamic. Try the options HTML > DOCTYPE > HTML4 Strict (as that is the only one working right now.)

As you can see, there is static content that has the SyntaxHighlighter plugin getting applied. But when I follow the above select options, and data is pulled from the database, it loses the plugin. I am assuming it is because the content is dynamic and I can't have stuff applied to it. This is the code I have.

jQuery:

$('#labels').live('change', function() {
    getScripts();
});

$.ajax({
    url: './db_scripts/get_scripts.php',
    success: function( data ) {
        var dataObj = jQuery.parseJSON( data );
        $.each(dataObj, function() {
            $('#code').html( this.code );
        })
        highlighter(); //after success, initiates highlighter 
    },
});

function highlighter() {
    SyntaxHighlighter.all();
}

Question:

How can I have the plugin applied to dynamic content? I have tried async: false but I don't think that is the solution. Thank you very much for your time.


Solution:

Explain (very nicely) below:

function highlighter() {
    SyntaxHighlighter.highlight()
}

1 Answer 1

5

As far as I see the problem is that the hightlight function is called just once (on window.load).

Try to call the SyntaxHighlighter.highlight() function yourself in your ajax callback function.

Update (elaboration):

SyntaxHighlighter.highlight() is the function that highlight all elements on the page that are marked as SyntaxHighlighter source code.

SyntaxHighlighter.all() just register the highlight() function for the window.load event. I think it's to be sure that the DOM is loaded before appling the SyntaxHighlighter.

If you call SyntaxHighlighter.all() more than once, it just registers the highlight() function once more. Because your are doing an ajax request, the window.load event isn't fired anymore. So you can call SyntaxHighlighter.highlight() directly.

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

2 Comments

What do you mean? I have hightlight() being called on the .success() of the final $.ajax call, do you mean additional to that?
I tried to use the complete: function and it did not work. I am assuming by calling :all it doesn't re-apply the event to the window?

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.