Reputation:
I want to get the node where the cursor is when it is being written
document.getElementById('parent').addEventListener('keypress', function(e) {
console.log(e.target);
});
.root {
padding-right: 1px;
}
#parent>div {
border-color: yellow;
float: left;
}
<div id="parent" contenteditable=true style="border: black 2px solid; height:200px">
<div class="root" id="1">Qué</div>
<div class="root" id="2">es</div>
<div class="root" id="3">Lorem</div>
<div class="root" id="4">Ipsum</div>
</div>
the problem is complicated because I am using for each word a div.
I need to use div so you can display the suggestions in the words (I'm doing a spellchecker)
Upvotes: 0
Views: 42
Reputation: 3389
Try this approach. I suggest you to use keyup event to get the final word after typed to generate your list of suggestions:
document.querySelectorAll('.root').forEach(function(el) {
// Do stuff here
el.onkeyup = function(e){
console.log(e.target);
};
});
.root {
padding-right: 1px;
}
#parent>div {
border-color: yellow;
float: left;
}
<div id="parent" style="border: black 2px solid; height:200px">
<div class="root" contenteditable="true" id="1">Qué</div>
<div class="root" contenteditable="true" id="2">es</div>
<div class="root" contenteditable="true" id="3">Lorem</div>
<div class="root" contenteditable="true" id="4">Ipsum</div>
</div>
Upvotes: 0
Reputation: 14768
You could use window.getSelection()
to get the actual node under the cursor:
document.getElementById('parent').addEventListener('keydown', event => {
const actualTarget = window.getSelection().anchorNode.parentNode;
console.log(actualTarget);
});
.root {
padding-right: 1px;
}
#parent>div {
border-color: yellow;
float: left;
}
<div id="parent" contenteditable="true" style="border: black 2px solid; height:200px">
<div class="root" id="1">Qué</div>
<div class="root" id="2">es</div>
<div class="root" id="3">Lorem</div>
<div class="root" id="4">Ipsum</div>
</div>
Upvotes: 2