I am trying to add an onkeypress event to a dynamically created p
element. This works fine in Firefox, Opera, and Chrome, but not in IE.
My code:
function newParagraphAfter(elem)
{
blockElemId++;
newPara = document.createElement("p");
newPara.id = 'block_' + blockElemId;
newPara.innerHTML = "Edit Here!";
elem.parentNode.insertBefore(newPara, elem.nextSibling);
document.getElementById('block_' + blockElemId).contentEditable = 'true';
document.getElementById('block_' + blockElemId).focus();
document.getElementById('block_' + blockElemId).onkeypress = function(event){return editKeypress(this, event)};
document.getElementById('block_' + blockElemId).onkeydown = function(event){return editKeydown(this, event)};
document.getElementById('block_' + blockElemId).onblur = function(){deleteIfBlank(this);};
}
Adding the id works in all browsers, and adding innerHTML also works. A test, of changing the background colour (document.getElementById('block_' + blockElemId).style.backgroundColor = "#666";
also worked in all browsers.
However, the lines adding onkeypress, onkeydown and onblur events, and also the .focus()
line do not work in IE.
Thank you in advance for any help,
Nico
UPDATE:
I would prefer not to have to use jquery if it can be avoided, simply because I like to be able to modify all of the code in my projects, and not use any 3rd party libraries. I would also have to learn a completely new way of coding, which I would rather not do if it can be avoided.
The contenteditable = 'true'
line works perfectly.
A working example can be found at www.brokenmyriad.com/editor.php