Search code examples
javascriptjquerymodal-dialogprettify

prettyPrint() only has an effect once. (google-prettify)


I have this JavaScript (with jQuery):

var g_files_added, socket, cookie, database = null;
var file_contents = [];
function viewFile(key, filename) {
    $('#title-filename').text(filename);
    $('.prettyprint').text(file_contents[key]);
    $('#viewFileModal').modal('show');
}
$(document).ready(function() {
    $(document).on('shown', '#viewFileModal', function(event) {
            prettyPrint();
    });
});

// Variables have been set in code not shown, irrelevant to problem.
// prettyPrint() is called everytime the #viewFileModal is shown,
// but its effect is only felt once.

So prettyPrint() is invoked every time the viewFileModal modal box (courtesy of Bootstrap) is shown, it's just that it only seems to have an effect once per page load.

I have tried commenting out prettyPrint() and entering at the JS console after making the modal box appear. It indeed only has an effect the first time the box is shown (per page load).

Any ideas? I have been stuck on this a while. I also tried putting the call to prettyPrint() in the viewFile function; but the effect is the same.

Thanks a lot.

Sam.


Solution

  • Calling "prettyPrint()" adds a class to your PRE tags named "prettyPrinted" after it has been prettified. The line below will remove all instances of the "prettyPrinted" class on your page so that the prettyPrint() function can re-prettify you're PRE tags. This can be done without dynamically adding PRE tags to DIVs.

    $('.prettyprinted').removeClass('prettyprinted');