views:

636

answers:

1

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

+1  A: 

Have a look at this: http://jsbin.com/uhiyi

Works fine in IE 8...

Yannick M.
Thankyou so much. Your answer helped me to find the problem in my code.
Nico Burns
Glad I could help
Yannick M.
So basically the code from the question was all right, and the problem was elsewhere?
Arjan
yes, i think it was.
Nico Burns