formatting a pre block to remove the first indent after Ajax has inserted data into a html code block?

Viewed 123

I usually use the below snippet to remove the first indent from my < pre >< code > blocks which works fine.

However im using an Ajax call to populate the html of the code block, which when completes it doesnt format anymore, ive tried to put the pre formatting code after the result is populated too but it still comes out with the large indent on the first line

I also tried to format the data.result with, which didn't work either

var pattern = data.result.match(/\s*\n[\t\s]*/);
results.html(data.result.replace(new RegExp(pattern, "g"),'\n'));

here is the code:

<script>
    $("pre").each(function(){
        var html = $(this).html();
        var pattern = html.match(/\s*\n[\t\s]*/);
        $(this).html(html.replace(new RegExp(pattern, "g"),'\n'));
    });
    var waiting = $('#waiting').hide()
    {% if task_id %}
        var task_id = "{{ task_id }}";
        var results = $('#results');

        get_task_info(task_id);

        function get_task_info(task_id) {
            $.ajax({
                type: 'get',
                url: '/monitoring/get_task_info/'+task_id,
                data: {'task_id': task_id},
                success: function (data) {
                    results.html('');
                    if (data.state == 'PENDING') {
                        waiting.show();
                    }
                    else if(data.state == 'SUCCESS'){
                        waiting.hide();
                        results.html(data.result);
                        $("pre").each(function(){
                            var html = $(this).html();
                            var pattern = html.match(/\s*\n[\t\s]*/);
                            $(this).html(html.replace(new RegExp(pattern, "g"),'\n'));
                        });
                    }
                    if (data.state != 'SUCCESS') {
                        setTimeout(function () {
                            get_task_info(task_id)
                        }, 2000);
                    }
                },
                error: function (data) {
                    results.html("Error!");
                }
            });
        }
    {% endif %}
</script>

EDIT: JS Fiddle Here https://jsfiddle.net/ajwill0/ty7s39ko/2/

oddly enough, in the fiddle neither option works, I have the large indent where there is supposed to be none...

1 Answers

So, the actual problem is white-space displayed between the end of pre tag and start of code tag

Option 1: css as mentioned by @Swati in comment

Option 2: Edit HTML and remove any white-spaces

e.g.

<pre><code>This is page rendered informatiom</code></pre>

<pre id="output_block"><code id="results"></code></pre>

JsFiddle Example: https://jsfiddle.net/Lar916t0/1/

If you are not allowed/able to edit HTML, you need to achieve the same with JavaScript

Related