Customizing SMF > Tips and Tricks

Select text and paste URL to create a text-link (like Slack)


If you're using Slack you may know this feature. You select some text that you wrote, then just paste a URL and the selected text magically turns into a link.

Well, I like this feature anyway, because it doesn't require fumbling with a link button. It's simply the fastest way to create text-links, so I wrote it for SMF.

Make sure your editors (quick reply and full editor textareas) have an id="message". Then load this script before the closing body tag.

--- Code: ---const messageBox = document.getElementById('message')
messageBox.addEventListener('paste', function(e) {
  const clipboard = (e.originalEvent || e).clipboardData.getData('text/plain')
  const regex = RegExp('https?://[^\s/$.?#].[^\s]*')
  const isUrl = regex.test(clipboard)
  if (isUrl) {
    const start = messageBox.selectionStart
    const finish = messageBox.selectionEnd
    const allText = messageBox.value
    const selected = allText.substring(start, finish)
    if (selected) {
      const newText = `${allText.substring(0, start)}[url=${clipboard}]${selected}[/url]${allText.substring(finish, allText.length)}`
      messageBox.value = newText

--- End code ---

Nifty. :) Just to be clear: I assume this works for 2.0.x. Will it also work with 2.1?

It works for any textarea with an id="message". So yeah, also for SMF2.1.

It does not work for the richText-Editor, because it's not a texarea, but an iframe with a contenteditable body.
I'm personally not interested in the richText-Editor. I might put some work into it in future, in the context of my involvement with SMF2.1.

Nobody uses the 2.0 wisiwyg editor anyway. It's too buggy. I wouldn't waste time on it.
SCE (used in 2.1) is pretty good, but personally I still tend to prefer using it in BBC mode.

I'm trying to do this, but its dosen't looks good, May be I don't have privilege to put URL  in my answer section.


[0] Message Index

Go to full version