Home > database >  Losing cursor position in editable div after replacing content
Losing cursor position in editable div after replacing content

Time:01-20

When I replace the whole content of an editable div by jquery, how can I prevent the cursor from moving to the start after any key press?

$('.editme').on('change keyup', function(e){
    wordFilter($(this).text());
    $(this).text(wordFilter($(this).text()));
}); 

I tried to save and restore the cursor position with selectionStart and selectionEnd, but it doesnt work on the editable div. Is there any simple way in jquery?

UPDATE:

WORKING SOLUTION: (with included caret plugin)

$('.editme').on('change keyup', function(e){
    var caretPos = $(this).caret();
    wordFilter($(this).text());
    $(this).text(wordFilter($(this).text()));
    $(this).caret(caretPos);
});

CodePudding user response:

One way to prevent the cursor from moving to the start after any key press when replacing the content of an editable div using jQuery is to use the caret plugin. The caret plugin allows you to easily get and set the cursor position within an input or textarea element. Here's an example of how you could use it in your code:

Try this:

var caretPos = $('.editme').caret();
$('.editme').on('change keyup', function(e){
    wordFilter($(this).text());
    $(this).text(wordFilter($(this).text()));
    $(this).caret(caretPos);
});

In the previous code, the caret function is used to get the current cursor position before the text is updated, and then the caret function is used again to set the cursor position to the same location after the text is updated. This will prevent the cursor from moving to the start after any key press.

This should work fine, However, if you want to use the latest version of jQuery it is better to use setSelectionRange to set the cursor position.

Code example:

var el = $('.editme')[0];
var start = el.selectionStart;
var end = el.selectionEnd;

$('.editme').on('change keyup', function(e){
    wordFilter($(this).text());
    $(this).text(wordFilter($(this).text()));
    el.setSelectionRange(start, end);
});

This method is a bit more verbose but it works on any browser and it is not dependent on any external library.

  • Related