Here's the parent div:
<div
id="comment"
placeholder="Your comment"
class="form-control ellipsesDropdown"
contenteditable="true"
@input="CommentChanged($event)"
> <!-- comments are divided into spans and divs with spans containg normal text and divs containing tags -->
<span>​</span>
</div>
Now when a user clicks a Tag, I create the Tag as follows:
const newTag = document.createElement('div');
newTag.setAttribute("tabindex", "-1");
newTag.style.cssText = "background-color: rgba(29,155,209,0.1); color: #1264a3; display: inline-block; font-weight: bold;";
const tagContent = document.createTextNode(`@${p}`); // imagine p is an input argument
newTag.append(tagContent);
// attach on key down event listener
newTag.onkeydown = function(event) {
console.log(event)
};
// add tag to the comment div
document.getElementById("comment")!.appendChild(newTag);
However, I get nothing when I press keys in the tag div, click events do work though. I took a look at How can I use a 'keydown' event listener on a div? and have added the tabindex attribute.
I've also tried attaching the event listener as:
newTag.addEventListener('keydown', function(event) {
console.log(event);
});
But this still doesn't work.
Any idea about what's going on?
EDIT: As requested, here's a codesandbox link: https://codesandbox.io/s/blue-bird-tdidr
EDIT 2: I've added more code from my project that basically implements to a certain extent what I'm trying to accomplish. Think about Twitter/Instagram/Slack, when you @someone as you're typing the post then perhaps some options appear for who to @ and when you click someone then that "tag" is added to your post. In the example, go ahead and write something, and include @, you'll see a list of options open, click either bread or toast and see it become a tag. What I'm trying to do it add the on keydown EventListener on the Tag so go ahead and see that it doesn't work!