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 :

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;
<textarea name="WPcomment" id="WPComment" placeholder="Add comments:">aaaaa</textarea>

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



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) {

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

$(function() {

You should place your preview code it within a function, then you can simply call it once the document has loaded.

The separate issue of your preview only rendering when you press the enter key, is because of the following if statement:

if(e.which == 13 && $(this).val().length > 0)

The e.which == 13 within your if is specifying that the code within the block should only be ran if the key pressed by the user was the enter key (code 13). By removing this portion of each if statement, any key pressed will execute the code within the block:

if($(this).val().length > 0)

Your function is call when keyup is trigger, but no after page load.

You must do it : Define function to call them when 2 different event are fired.

$(function() {
        function GetHtml(){
                var html = $('.html').val();
                return html;

        function GetCss(){
                var Css = $('.css').val();
                return Css;

        var previewRendering = function(){
            var targetp = $('#previewTarget')[0].contentWindow.document;

          var html = GetHtml();
          var css = GetCss();

          $('head', targetp).append('<style>' + css + '</style>');



        $(document).ready(function() {


This code can not work because load event is only compatible with this list of HTML tags: body, frame, iframe, img, input type="image", link, script, style



Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.