jakiestfu / Medium.js

A tiny JavaScript library for making contenteditable beautiful (Like Medium's editor)
http://jakiestfu.github.io/Medium.js/
4.39k stars 404 forks source link

Convert URLs to clickable A tags #172

Open pixeline opened 8 years ago

pixeline commented 8 years ago

Medium.js is quite impressive. I'm using it on http://do-not-forget.me as it provides a safe way to use contentEditable across browsers.

I'm now looking for a way to have the editable innerHTML to parse for hyperlinks, and convert them to A tags.

I figured I should use a callback on the keyup event, callback which parses the innerHTML for urls using a regex. It sort of works but it messes up with the caret position.

Do you recommend any method for controlling the caret position, or for parsing the content for links?

Thank you for all your help. Alex.

pixeline commented 8 years ago

Digging into the source code, I found a way to put the caret at the end of the content zone

medium.cursor.moveCursorToEnd(editable);

Is there a built-in way to store the caret position, perform the autolinking, then put the caret back at that position?

pixeline commented 8 years ago

Ok, for future reference, this is how i managed to autolink urls (using autolink.js)

// ON KEYUP EVENT,  PARSE FOR URLS.
    caret_position = window.rangy.saveSelection();

    // remove previous anchored version of the content
    var a = editable.getElementsByTagName('a');
    while(a.length) {
        unwrapAnchors.call(a[a.length - 1]);
    };

    // convert urls to anchors
    medium.value( autolinker.link( editable.innerHTML ));

    // restore caret position
    window.rangy.restoreSelection(window.caret_position);