Get cursor position in contenteditable div

I found the following code here on SO to get the cursor position of a contenteditable div, however it always returns 0.

Function to get position:

new function($) { $.fn.getCursorPosition = function() { var pos = 0; var input = $(this).get(0); // IE Support if (document.selection) { input.focus(); var sel = document.selection.createRange(); var selLen = document.selection.createRange().text.length; sel.moveStart('character', -input.value.length); pos = sel.text.length - selLen; } // Firefox support else if (input.selectionStart || input.selectionStart == '0') pos = input.selectionStart; return pos; } } (jQuery); 

The code I use to verify it:

 $('div.MESSAGE_OF_DAY').keyup(function() { alert($(this).getCursorPosition()); // always returns 0??? }); 

I use Chrome (8.0.552.215) if that makes a difference.

+1
source share
1 answer

The function you discovered is designed to search for a carriage or highlight in an input or text field, and not for content. The position of the carriage / select border can be obtained using the DOM node and the offset within that node using the browser Selection object to get the Range . I suggest reading about these objects (the links I provided are a good starting point). In Internet Explorer, this process is completely different, but you can use my Rangy library to fix the differences.

+8
source

Source: https://habr.com/ru/post/1379966/


All Articles