Reputation: 833
Is it possible to get the positions of cursor of writing (absolute x,y pixels positions of the last character) inside the input textarea
Note: its not just count number of characters, but I have to deal with new lines, for example, if the user type the Enter key (I have to detect the new position in pixels of the last character
I want this because i need to display a popup with suggestions while users type texts
if you have an example in reactjs or in classic javascript (not jquery) please share with your code
i hope that my question was clear.
Thank you in advance
Upvotes: 0
Views: 114
Reputation: 833
Finally i found a solution: here the code for reactjs
var text = this.refs.areatext,
coords = {};
var carPos = text.selectionEnd,
div = document.createElement("div"),
span = document.createElement("span"),
copyStyle = getComputedStyle(text);
[].forEach.call(copyStyle, function(prop){
div.style[prop] = copyStyle[prop];
});
div.style.position = "absolute";
document.body.appendChild(div);
div.textContent = text.value.substr(0, carPos);
span.textContent = text.value.substr(carPos) || ".";
div.appendChild(span);
coords = {
"TOP": span.offsetTop,
"LEFT": span.offsetLeft
};
document.body.removeChild(div);
this.setState({x:coords.LEFT,y:coords.TOP})
for javascript
(function() {
var text = document.querySelector(‘textarea’),
indicator = document.querySelector(‘.indicator’),
getCoord = function(e) {
var carPos = text.selectionEnd,
div = document.createElement(‘div’),
span = document.createElement(‘span’),
copyStyle = getComputedStyle(text),
coords = {};
[].forEach.call(copyStyle, function(prop){
div.style[prop] = copyStyle[prop];
});
div.style.position = ‘absolute’;
document.body.appendChild(div);
div.textContent = text.value.substr(0, carPos);
span.textContent = text.value.substr(carPos) || ‘.’;
div.appendChild(span);
coords = {
‘TOP’: span.offsetTop,
‘LEFT’: span.offsetLeft
};
console.log(coords);
indicator.style.left = coords.LEFT + ‘px’;
indicator.style.top = coords.TOP + ‘px’;
document.body.removeChild(div);
};
text.addEventListener(‘input’, getCoord);
}());
Upvotes: 1
Reputation: 937
Please check this code, i have made cursor detection in javascript, hope will help you.
window.onload = init;
function init() {
if (window.Event) {
document.captureEvents(Event.MOUSEMOVE);
}
document.onmousemove = getCursorXY;
}
function getCursorXY(e) {
document.getElementById('cursorX').value = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
document.getElementById('cursorY').value = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}
<html>
<body>
<input type="text" id="cursorX" size="3"> X-position of the mouse cursor
<br /><br />
<input type="text" id="cursorY" size="3"> Y-position of the mouse cursor
</body>
</html>
Upvotes: 0