0

I have these HTML codes in 'body' tag:

<body>
    <center>
        Hello!<br />
        <textarea cols="65" rows="10" id="code"></textarea>
    </center>
</body>

And I want to place all of my page codes in above textarea with this codes in jQuery:

$("textarea#code").val( $('body').html() );

OK, now I want to let user change the HTML of 'body' in that 'textarea' using this:

$("textarea#code").change(function(){
    $('body').html( $(this).val() );

    $("textarea#code").val( $('body').html() );
});

After first change all things are OK and HTML changes successfully, but after doing that, the user can not change HTML for the second time! In other words, JavaScript didn't load.

Here's my snippet:

$("textarea#code").val( $('body').html() );

$("textarea#code").change(function(){
    $('body').html( $(this).val() );
    
    $("textarea#code").val( $('body').html() );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
    <center>
        Hello!<br />
        <textarea cols="65" rows="10" id="code"></textarea>
    </center>
</body>
Goran Stoyanov
  • 2,311
  • 1
  • 21
  • 31
Arman
  • 11
  • 3

3 Answers3

3

You need delegation:

$("textarea#code").val($('body').html());
$(document).change("textarea#code", function (e) {
    $('body').html($(e.target).val());
    $("textarea#code").val($('body').html());
});

JSFIDDLE

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
1

html method as setter is destructive, i.e. it replaces all the contents by parsing the passed value and generating new elements. Event handlers are bound to elements and each DOM object is unique. After using html method the old elements will be removed, so the event handlers attached to them won't function anymore. You should use event delegation in this case.

That being said using a textatea here for modifying HTML content of the entire page doesn't make a lot of sense. If you want to edit the page dynamically you can use a WYSIWYG editor or contentEditable attribute instead.

Ram
  • 143,282
  • 16
  • 168
  • 197
0

HTML in your body is dynamically changing. You have to use,

$(document).on('change','textarea#code',function(){
    $('body').html( $(this).val() );
    $("textarea#code").val( $('body').html() );
});

instead

$("textarea#code").change(function(){
    $('body').html( $(this).val() );

    $("textarea#code").val( $('body').html() );
});

JSFIDDLE DEMO

Sampath Liyanage
  • 4,776
  • 2
  • 28
  • 40