javascriptjqueryhtmlcsslive-preview

Live HTML/CSS preview from a div tag and not a text area tag


I want to create a live HTML/CSS preview on a page.

But the code will not be given using textareas. The code is going to be fixed in the page (div).

I want the user to be able to alter the code and that will reflect on the live preview box.I have created the page where you can change parts of the script text (for amateurs). You can preview that here : http://apolosiskos.co.uk/HTML-CSS-EDITOR/index3.html

01) The live preview does not work if I replace the textarea with a div.

02) Even if I use the textareas, the live preview does not work because in my HTML script I am using the codeand the xmp tags.

--> Snippet that works with a textarea but not with a div :

var wpcomment = document.getElementById('WPComment');

wpcomment.blur = wpcomment.onkeypress = function(){
    document.getElementById('prevCom').innerHTML = this.value;
}
#prevCom
{
  background:#124;
  color:#fff;
  min-width:20px;
  min-height:50px;
  font-size:25pt;
}
<textarea name="WPcomment" id="WPComment" placeholder="Add comments:">aaaaa</textarea>

<div id="prevCom"></div>


Solution

  • with no success. Is there any other addEventListener() method I can replace keyup with?

    Yes, blur

    If you would like to add keydown events on a <div> element, you can do the following:

    First, you need to set the tabindex attribute:

    <div id="a-div" tabindex="1" />
    

    Then, (2) Bind to keydown:

     $('#mydiv').bind('keydown', function(event) {
        //console.log(event.keyCode);
     });
    

    If you would like your div to be "focused" from the start:

    $(function() {
       $('#mydiv').focus();
    });