1

I’m trying to add a link on a selected text (inside a contenteditable). The link window is just an input field. The problem is that after I select some text, click the link button to show the link input field and focuses, I lose the selected text.

How does WYSIHTML5 do it: http://xing.github.com/wysihtml5/ ? If you click on the link icon in the toolbar and focus on the link’s input field, your selected text stays selected.

Alternatively, I could save the selection in a variable, but how do I call it on blur()? I have to make the variable global? I‘m getting “selected not defined” when on blur().

HTML:

<button class="link_button">L</button>
<div class="link window hidden"><input name='link' class='link_input' autofocus='autofocus' value='http://'/></div>

jQuery:

$('.link_button').click(function() {
    $('.link').toggleClass('hidden');
});

$('.link_input').focus(function() {
    var selected = saveSelection();
})

$('.link_input').blur(function() {
    restoreSelection(selected);
})

function saveSelection() {
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            return sel.getRangeAt(0);
        }
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange();
    }
    return null;
}

function restoreSelection(range) {
    if (range) {
        if (window.getSelection) {
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.selection && range.select) {
            range.select();
        }
    }
}

Any ideas? Thanks!

2
  • If the selection is not disappearing then WYSIHTML5 must either be using an iframe for the editable area (a common technique with WYSIWYG editors; it used to the only way to do it in Firefox in the old days) or faking the selection. I suspect it's the former.
    – Tim Down
    Feb 1, 2013 at 10:03
  • @Alex It's probably an old question but I am wondering if you have found any solution so far ? I have the same issue! Thanks
    – medBouzid
    May 5, 2016 at 20:14

1 Answer 1

0

You can use rangy library for easy selection management.

  1. This is a cross-browser supported library.
  2. Simple to use
2
  • No, I’d like to do it without a library.
    – Alex
    Jan 31, 2013 at 0:40
  • Then check the code in this library. You will get how to get the selection and save it correctly.
    – Wolf
    Jan 31, 2013 at 6:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.