Search code examples
javascriptcontenteditable

how do i select an entire url address in contenteditable


in contenteditable, links don't work, so i'm thinking the best solution is to at least be able to select an entire url with one click or two clicks when the cursor is in any part of the url, then right-click and go to the site. is there a javascript solution to this, something similar to android phone's long-press-select and paste?

<div contenteditable="true">some text here, then the complete url https://gizmodo.com/e-ink-kaleido-3-gallery-3-foldable-color-e-readers-1848842166 but i just want to select the url with one or two clicks, how? </div>

contenteditable:

some text here, then the complete url https://gizmodo.com/e-ink-kaleido-3-gallery-3-foldable-color-e-readers-1848842166 but i just want to select the url with one or two clicks, how?

Solution

  • You could replace the url strings with anchor tags and attach an onclick listener to navigate to the url on click:

    text.innerHTML = text.textContent.replace(/https*:\/\/[^\s]+/gmi, (match) => `<a style="cursor:pointer" href="${match}">${match}</a>`);
    
    [...text.children].forEach(a => a.onclick = (e) => window.open(a.href))
    
    text.onblur = e => {
    e.target.innerHTML = e.target.textContent.replace(/https*:\/\/[^\s]+/gmi, (match) => `<a style="cursor:pointer" href="${match}">${match}</a>`);
    [...text.children].forEach(a => a.onclick = (e) => window.open(a.href))
    }
    <div id="text" contenteditable="true">some text here, then the complete url https://gizmodo.com/e-ink-kaleido-3-gallery-3-foldable-color-e-readers-1848842166 i just want to select the url with one or two clicks, how? Another url here: https://gizmodo.com/e-ink-kaleido-3-gallery-3-foldable-color-e-readers-1848842166
    </div>

    (The navigation in the snippet iframe is prevented but it should work in a normal window)