Tuesday, November 30, 2021

javascript snippet: link-ify currently selected text in textarea

I'm rewriting my blog's backend edit features in PHP and vanilla javascript... admittedly that's a cringe-inducing mis-ambition of a target platform for some, but certainly a step up from the ancient Perl CGI and JQuery I was using before.

Features of my editing including managing image uploads w/ resizing and gallery-making, a tag system, special "blockquote" content, twitter quotes, etc. 

A while back I talked about linky, my preferred way of shortcutting having to type <a href=""></a> all the time - basically for the current selection only, if it starts with "http", assume that is a URL we are linking to, otherwise assume the selection is the clickable text.

Here is vanilla JS to do that (vs my earlier jQuery textrange() stuff)

function linky(textarea){
    const len = textarea.value.length;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const sel = textarea.value.substring(start, end);    
    const replace = sel.indexOf('http') === 0 ? 
        `<a href="${sel}"></a>` 
        : `<a href="">${sel}</a>`;
    textarea.value =  textarea.value.substring(0,start) 
                + replace 
                + textarea.value.substring(end,len);
}

(vanilla text replace cribbed from here... don't know or care that much if this busts on IE)

"textarea" is the DOM element... I was thinking about how to know which textarea last had the focus, so I can apply the same function to multiple textareas without having to give each textarea its own launching link. I think I will add an onfocus to each textarea that is eligible for linky-fication to register itself globally, and the last such textarea to have done so will be the one used in the function. Crude but good enough.

Stepping back up to the UX of it... the fidliness/ugliness of <a href=""></a> was the kind of thing that led Aaron Swartz and John Gruber to invent Markdown - as Swartz put it "Why should I have to cover everything in annoying pointy brackets just so it knows what I mean?" 

I don't mind pointy brackets that much - I have a strong preference for working on the level of the target  platform (i.e. DOM markup and javascript that are consumed natively by the browser without a pre-processing step) so long as that level is still reasonably expressive and not too onerous, so I wouldn't consider a separate markup language. (The markdown-ish thing thing I do do, though, is replace \n with <br>...)

The other UX solution for composing links I often see is a popup dialog that has "URL" in one field and clickable text in another. I always get confused about which is which, so I find my "put in href initial boilerplate" method more well-suited to my thinking.


No comments:

Post a Comment