I have a set of 3 pre tags that are editable. When someone is on one of the lines and hits 'enter', I want it to insert a new tag below (in the document tree) the one it is on. I have tried to put an event handler on the tags so that this occurs, but the 'onkeypress' doesn't seem to be firing.
<script>
function handlers(){
var pres = document.getElementsByTagName("pre");
for(i=0; i<pres.length;i++){
pres[i].addEventListener("onkeypress", function(e){
if(e.which != 13) return;//the ENTER key
var tag = e.srcElement;
if(tag.nextSibling){
var next = tag.nextSibling;
var newPre = document.createElement('pre');
tag.nextSibling = newPre;
newPre.nextSibling = next;
}
var tree = document.getElementById("tree");
tree.innerHTML = document.getElementByTagName().length;
});
}
}
</script>
<body onload="handlers();">
<div id="editor" contentEditable="true">
<pre>1</pre>
<pre>2</pre>
<pre>3</pre>
</div>
<div>
<p id="tree"></p>
</div>
</body>
You are iterating over the array of elements incorrectly, and you are not attaching event listeners correctly.
I recommend changing your for loop to:
You can read up on attaching event listeners here
Additionally, it would appear: http://jsfiddle.net/vZYpX that the source of the keypress event under "contentEditable" is the actual element that is "contentEditable". So you have to either make the
<pre>
s content editable (and not the div), or attach the listener to the parent div (that is currently contentEditable).