I am having small issue with my code mirror preview. For some reason will not dectect when new line is created in editor.

Question: How to make sure that the code mirror preview dectects a new line and displays it correctly?

Codepen Example Here

Script

<script type="text/javascript">
$(document).ready(function() {
    var editor = document.getElementById('text-editor');

    $("#text-editor").each(function (i) {

        editor = CodeMirror.fromTextArea(this, {
            lineNumbers: false,
            lineWrapping: true,
            mode: 'html',

        });

        editor.on("change", function() {
            document.getElementById('question-preview').innerHTML=editor.getValue();
        });


        $('button').click(function(){

            var val = $(this).data('val');
            var string = editor.getSelection();

            switch(val){

                case 'bold': 
                    editor.replaceSelection('<b>' + string + '</b>');
                break;

                case 'code': 
                    editor.replaceSelection('<pre>' + string + '</pre>');
                break;
            }
        });
    });
});

</script>

Html

<div class="container">

<div class="row">

<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-default"  onLoad="text_editor();">
<div class="panel-heading">
<button type="button" data-val="bold" class="btn btn-default">Bold</button>
<button type="button" data-val="hyperlink" data-toggle="modal" data-target="#hyperlink" class="btn btn-default">Link</button>
<button type="button" data-val="code" class="btn btn-default ">Code</button>
</div>
<div class="panel-body">
<textarea id="text-editor" name="text-editor" class="form-control"></textarea>
</div>
</div>
</div>

</div>

<div class="row">

<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div id="question-preview"></div>
</div>

</div>

</div>

Hi,

you could set the line separator into getValue(), for example at line 28:

editor.getValue('<br>')

But this will add the <br> also in the code blocks, otherwise you can apply a CSS rule to #question-preview:

#question-preview {
    white-space:pre-line;
}

And change the #question-preview pre code white-space rule at your preferences:

#question-preview pre code {
    padding: 0;
    white-space: inherit;
}

Docs: http://codemirror.net/doc/manual.html#getValue

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.