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>

2
  • It's not that JavaScript didn't load, it's that you ran into an infinite loop. You update the value of the textarea inside the change event, which re-fires the change event, and it repeats. Commented Nov 16, 2014 at 8:31
  • Do you consider accepting an answer? Commented Nov 25, 2014 at 19:33

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.