views:

309

answers:

2

I am trying to add an onKeyPress event to a dynamically created html element using javascript. In practise, the element is added, the id is assigned, and the innerHTML added, but the onmouseover, onmouseout, and onKeyPress (2nd last line) events are not added to the element. The last line (.focus()) does work.

Code:

function newParagraphAfter(elem)
{
blockElemId++;
newPara = document.createElement("p");
newPara.id = 'block_' + blockElemId;
newPara.contentEditable = 'true';
newPara.onmouseover = "this.style.border='1px dashed white';";
newPara.onmouseout = "this.style.border='none';";
newPara.innerHTML = "Edit Here!";
elem.parentNode.insertBefore(newPara, elem.nextSibling);
document.getElementById('block_' + blockElemId).onKeyPress = "return editKeypress(this, event)";
document.getElementById('block_' + blockElemId).focus();
}

Any help greatly appreciated,

Nico

+1  A: 

Lowercase your onKeyPress and use a function

document.getElementById('block_' + blockElemId).onkeypress = function(e) {
    if(!e) e = event;
    return editKeypress(this, event)
};

Edit: Added bobince's advice for a more cross-browser friendly answer.

Gordon Tucker
Thanks a lot Gordon, I'd always wondered what the point of those anonymous functions was.
Nico Burns
This will only work on IE, due to the global `window.event`. Everywhere else, the event is passed in as an argument to the handler function. You should just set `newPara.onkeypress= editKeypress`, and in `editKeypress` check for an argument. ie. traditionally: `function editKeypress(e) { if (!e) e= window.event; ...`
bobince
+2  A: 

I do not think you can assign strings to event handlers - Javascript can coerce data but not to this degree. What you need to do instead is write you code as a function and then assign the function to the event handler

mfeingold