user4419336
user4419336

Reputation:

clone div is not displaying same code straight away

On my code I have a area where I can preview any code as I am typing. The problem I am having is when I select some text and then click on button either bold, italic, pre. The preview area does not display same code straight away.

Question How can I make sure that the preview area when I select some text and then click on a button then it will display correct code below straight away. At the moment just displays plain text.

Live Example

Codepen Code View

Codepen Full View

Script

<script type="text/javascript">

$('#code_view').on('click', function(e) {
    var code = $('#editable').clone();
    $('#preview').html(code);
});

$('#editable').keyup(function(){
    $('#code_view').trigger('click');
});

$('#editable').each(function(){
    this.contentEditable = true;
});
</script>

HTML

<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-sm-12">
<div class="form-group">
<input type="text" class="form-control" name="title" placeholder="Title" />
</div>
</div>
</div>

<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-sm-12">
<div class="panel panel-wmd">
    <div class="panel-heading">
        <div class="clearfix">
            <div class="pull-left">
                <button id="bold" class="btn btn-default">B</button>
                <button id="italic" class="btn btn-default"><i>I</i></button>
                <button id="pre" class="btn btn-default">{}</button>
                <button id="code_view" class="btn btn-default">Code View</button>
            </div>
            <div class="pull-right">
            </div>
        </div> 
    </div>
    <div class="panel-body">

        <div id="editable"></div>
    </div><!-- .panel-body -->
</div><!-- .panel -->
</div>
</div>

<div class="row">
    <div class="col-lg-12 col-md-12 col-sm-12 col-sm-12">
        <div id="preview"></div>
    </div>  
</div>
</div><!-- .container -->

Upvotes: 0

Views: 35

Answers (1)

Help
Help

Reputation: 1156

Seeing at the code you have done everything right. For achieving the result instantly on click of the button you need to call the code_view click function on the functionality buttons.

Updated code:

Code Pen

Hope this helps you.

-Help :)

Upvotes: 2

Related Questions