linkifyjs icon indicating copy to clipboard operation
linkifyjs copied to clipboard

Linkify in Textarea

Open vaibviad opened this issue 10 years ago • 2 comments

I am using linkify in textarea & i have autosave function in it. after every 3 secs the text is saved in db .I am calling linkify before saving in db. What problem i am facing is the focus of cursor/caret is lost due to linkify .. I keep on writing and after autosave cursor is lost its position.. I am using froala-editor as my text editor. Can u suggest some tweaks to solve this .. @nfrasser

vaibviad avatar Mar 31 '15 06:03 vaibviad

Hmm, interesting use case. Currently Linkify is designed to run on static HTML (as opposed to content-editable textareas like froala-editor). You could instead apply Linkify to your content once it renders on a web page, rather than the text editor.

i.e.,

<textarea>My content</textarea>

...

<div id="content">My Content</div>
$('#content').linkify(); // rather than $('textarea').linkify()

For future releases we'll definitely look into ways of making Linkify play nicely with WYSIWYG editors.

nfrasser avatar Mar 31 '15 18:03 nfrasser

Thanks @nfrasser for reply and considering as enhancement. For now i have solved the issue by saving the caret position and restoring it back after the linkify is called. below i am sharing my code which might help you to accomplish the enhancement

if (window.getSelection && document.createRange) {
    saveSelection = function(containerEl) {
        var range = window.getSelection().getRangeAt(0);
        var preSelectionRange = range.cloneRange();
        preSelectionRange.selectNodeContents(containerEl);
        preSelectionRange.setEnd(range.startContainer, range.startOffset);
        var start = preSelectionRange.toString().length;
        return {
            start: start,
            end: start + range.toString().length
        }
    };

```
restoreSelection = function(containerEl, savedSel) {
    var charIndex = 0, range = document.createRange();
    range.setStart(containerEl, 0);
    range.collapse(true);
    var nodeStack = [containerEl], node, foundStart = false, stop = false;

    while (!stop && (node = nodeStack.pop())) {
        if (node.nodeType == 3) {
            var nextCharIndex = charIndex + node.length;
            if (!foundStart && savedSel.start >= charIndex && savedSel.start = charIndex && savedSel.end 

. Then you can call the sequence as follows

SaveCARETpos- Linkify - RestoreCARETpos - SavetoDB

Courtesy http://stackoverflow.com/questions/29362809/linkify-in-textarea-jquery/29363154?noredirect=1#comment46919414_29363154 http://stackoverflow.com/questions/13949059/persisting-the-changes-of-range-objects-after-selection-in-html/13950376#13950376

vaibviad avatar Apr 01 '15 06:04 vaibviad