search

Home  >  Q&A  >  body text

Toggle text area to switch between HTML code and preview

I want to use the text area to switch between HTML code and preview html

When clicked on the HTML, it will show the code for the hidden text area When clicking HTML again it will show

again

I want to design something like this

I have tried before

<style>
.container {
    width:500px;
    position: fixed;
}

.right-element {
    background: red;
    display: inline-block;
    position: absolute;
    right: 0;
}
</style>

<div class="container">
    <div class="right-element">
        Preview
    </div>
  <textarea id="w3review" name="w3review" style="position:relative;width:100%;height:75%;resize: none; " ><h3>At w3schools.com you will learn how to make a website. They offer free tutorials in all web development technologies.</h3></textarea>    
</div>

P粉006977956P粉006977956239 days ago437

reply all(1)I'll reply

  • P粉831310404

    P粉8313104042024-04-01 10:54:05

    You can have another div dedicated to showing the preview. Then, when the user switches the HTML view, insert the textarea's value into the innerHTML of the div and display it.

    But this may expose your application to XSS attacks, so use it with caution.

    $('.right-element').click(function() {
      $(this).toggle()
      $(this).siblings().toggle()
      togglePreview()
    })
    
    let showPreview = false
    const w3Preview = $('#w3review-preview')
    
    function togglePreview() {
      if (!showPreview) {
        w3Preview.html(w3review.value)
        w3Preview.show()
        $(w3review).hide()
      } else {
        w3Preview.hide()
        $(w3review).show()
      }
      showPreview = !showPreview
    }
    #html,#w3review-preview{display:none}.container{position:fixed;width:500px}.right-element{background:red;display:inline-block;position:absolute;right:0;z-index:1}
    sssccc
    
    Preview
    HTML

    reply
    0
  • Cancelreply