Reputation: 8062
I'm looking for a way to capture the specific character (or character index in text) after the user clicks on it inside of a contenteditable
div. Just to provide an example, please consider the following HTML:
<div contenteditable="true">
Hello world
</div>
Suppose the user clicks right between "o" and "r", is there a way to know that, using JavaScript?
I'd imagine this would be covered by the Selection API but all my inquiry so far has produced me nothing.
I appreciate any help that you can give me.
Upvotes: 0
Views: 50
Reputation: 1085
You can always do something like this. Codepen Link
I have put an alert in so that you can see that it does indeed know what you clicked and if you click a space as in between Hello and World it knows as well.
var div = document.getElementById("div");
function clickify (e) { var arr = (typeof e.innerText !== 'undefined') ? e.innerText.split("") : e.textContent.split(""), max = arr.length, i = 0, template = "$c", result = "";
for (; i < max; i += 1) {
result += template.replace("$c", arr[i]);
}
e.innerHTML = result;
}
clickify(div);
Upvotes: 1
Reputation: 731
You can see the caret position, i have done a small snippet for you here. Have a look at it.
enter code here
http://codepen.io/19sthil80/pen/pEooVR
Upvotes: 1