Fix: Trim Trailing Whitespace when Pasting Text into Input Fields #lock #whitespace

I randomly came across Lock: Trim Trailing Whitespace when Pasting Text into Input Fields which was quite unfortunately locked as soon as it was created. It has an annoying bug.

I know what you are going for by locking comments immediately in that section- but in the spirit of the open web and the fact that you have high enough SEO that your results pop up on Google, please consider revising this practice and leaving your posts open. It’s just not healthy or condusive. Thank you for hearing me out.


In Lock: Trim Trailing Whitespace when Pasting Text into Input Fields there’s a confusing edge case: If a textbox already has text in it, the provided code snippet will surprise users by overwriting text. Unfortunately a more correct answer is sadly much more verbose than the 3 line solution provided. But nonetheless…

Here’s an approximate solution you could revise on your post:

input.addEventListener('paste', function(event) {
    event.preventDefault();
    const pastedText = (event.clipboardData || window.clipboardData).getData('text').trim();
    // Must take in to account the position of the cursor and whether any text was selected.
    const start = input.selectionStart;
    const end = input.selectionEnd;
    const currentValue = input.value;
    input.value = currentValue.slice(0, start) + pastedText + currentValue.slice(end);
    input.setSelectionRange(start + pastedText.length, start + pastedText.length);
  });

Tagging for visibility @travis.evers