0

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Thanks a lot Gordon, I'd always wondered what the point of those anonymous functions was.
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; ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.