I've got a div that is contenteditable=true that has child divs. I'm trying to attach a keydown event to one of the child divs to clear out the default text. However, I cannot get the keydown event to work. A click event works fine so I'm not sure what I'm missing.
First I'm trying to give focus to the outer div that has contenteditable set to true.
var $editableDiv = $("#ID");
$editableDiv.focus();
Then I want to move the cursor to the div I want them typing in.
var focusDiv = $editableDiv.children("div").children("div")[0];
var sel = window.getSelection();
var range = document.createRange();
range.setStart(focusDiv, 0);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
Now I try and attach the keydown event:
$(focusDiv).on("keydown", function (e)
{
var $target = $(e.target);
if ($target.text() === "Enter comment here")
{
$target.text("");
}
}
But this never fires with the keydown event. It will fire if I change it to a click event and click on it. Does it have something to do with keydown not working on contenteditable tags? Reading the jquery manual:
The keydown event is sent to an element when the user first presses a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.
Could it be a problem with the div not truly being able to "take focus?" Perhaps if I give it a tabIndex?