1

<p>Select Some of This Text</p>
<span>Now click this</span>

Is it possible to make it so that when you click on the <span> it doesn't remove the selection of the <p> or stores it somewhere? Maybe using the onblur event?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
MBJH
  • 1,571
  • 3
  • 17
  • 36
  • What is your use case for doing that? Also, can you please clarify what does it mean when you say "stores it somewhere"? – Nishant Feb 16 '18 at 21:41
  • 2
    @Nishant I think “stores it somewhere” is referring to the possible solution of saving the bounds of the text selection before the browser clears it, then re-selecting that range immediately after the browser does its own setting of the selection. This could be done using whatever the equivalent of [`inputElement.setSelectionRange`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange) is for non-`input` elements. (That equivalent is `Range` – see [Can you set and/or change the user’s text selection in JavaScript?](https://stackoverflow.com/q/4183401/578288).) – Rory O'Kane Feb 16 '18 at 22:22

1 Answers1

2

One method is to prevent the selection of text within the “Now click this” button, using the CSS explained in How to disable text selection highlighting?. With this CSS, clicks on the button won’t change the selection, including if there is an existing selection.

.unselectable {
  -webkit-touch-callout: none;
    -webkit-user-select: none;
     -khtml-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
            user-select: none;
}
<p>Select Some of This Text</p>
<span class="unselectable">Now click this</span>
Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131