Me trying to find out caret position coordinates with respect to document(Whole Web Page) in a TextArea or Input of type="text" on JavaScript HTML DOM Events functions like onkeydown, onkeypress, onkeyup etc...
For this I created the below HTML...
<input dir="rtl" type="text" id="TEST_INPUT" onkeydown="myFunction(this)"></input>
<textarea dir="rtl" id="TEST_TEXTAREA" onkeyup="myFunction(this)"></textarea>
And running the below JavaScript...
<script type="text/javascript">
/* Main Function
----------------------------------------------- */
function myFunction(Desired_ID){
// Extra Codes Here ETC...
document.getElementById(Desired_ID.id).style.backgroundColor = "red";
// Extra Codes Here ETC...
var coords = getSelectionCoords(Desired_ID);
alert(coords.left + ", " + coords.top);
// Extra Codes Here ETC...
}
/* Get Caret XY Coordinate
----------------------------------------------- */
function getSelectionCoords(Desired_ELEMENT) {
// ------>>> What To Do Here Is The Problem To Cover All Browsers <<<------
return {left:x,top:y};
}
</script>
I searched in StackOverflow and found many one but everyone have some sort of problems while using or running that are shared below...
Where mine working DEMO is at https://jsfiddle.net/qjkkqdg2/ on which I am working out so can your share any tip or idea to go through it...???
After keep working and trying, I found my desired answer and here I am sharing it below in the form of code that you can see at https://jsfiddle.net/qjkkqdg2/1/ also...
And this code of id by https://github.com/component/textarea-caret-position. Thanks for him...
LIMITATION:
Its only giving coordinate with respect to element but I want to get it with respect to whole document...
To fix this limitation, I added another function that will find out element coordinate with respect to whole document so just add the below function also...
So finally our Main Function will be now as...
SO finally our last DEMO is at https://jsfiddle.net/qjkkqdg2/2/