0
votes

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?

1
I pretty much answered my own question. The problem is I was giving focus to the outer div then moving the cursor into the inner div. Then trying to call the keydown event on the inner div that wasn't given the focus in the first place. But if I give focus to the inner div, it gets a strang hashed box around it that I don't like. Not sure what to do about that.griztown

1 Answers

4
votes

The problem was where I was applying focus. I was applying focus to a parent div then moving the cursor to one of the children and trying to apply the keydown event to that child. Once I applied it to the parent it worked.