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 code
and 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>
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:
Then, (2) Bind to keydown:
If you would like your div to be "focused" from the start:
You should place your preview code it within a function, then you can simply call it once the document has loaded.
https://jsfiddle.net/michaelvinall/4053oL1x/1/
The separate issue of your preview only rendering when you press the enter key, is because of the following
if
statement:The
e.which == 13
within yourif
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 eachif
statement, any key pressed will execute the code within the block: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.
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