Prevent text selection from exiting a div
css, html, javascript, jquery
Solution
You could achieve this with jQuery, however, the easiest and most lightweight option I know of would just be to do what companies like Google have always done:
Place the text that is going to be highlighted inside an input or textarea box.
Demo here
<textarea>Text that will be highlighted here..</textarea>
If you want it to be somewhat hidden, set `border:none;`
textarea {
border:none;
width:400px
resize:none;
}
If you want to embed maps from Google, Youtube videos, or a facebook feed, all these companies use this approach. I'm pretty sure this is your best option.
If you want the text to be auto selected on click, use some JS like:
function SelectAll(id) {
document.getElementById(id).focus();
document.getElementById(id).select();
}
Problem
I have a `div` that displays some text that the user might want to highlight to copy and paste or the like. While kicking the tires of that design, I noticed it was easy to end up selecting content beyond that `div` simply by dragging the mouse too far. I'd like to avoid this issue by preventing the selection from leaving the relevant `div`, but I haven't been able to find any way to do it. One possible solution might be applying `user-select:none` (as described here) everywhere but that particular `div`, but that won't work in this case because there are other `div`s which need to have selectable text. Conceivably jQuery could be used to change `div` styles so that `user-select:none` would apply to everything but the `div` you're selecting text in, but I feel like there has to be a simpler way to go about it, possibly even with just CSS. Anyone know how to do this? Edit: Josh C's answer below does the trick. Here's a JS fiddle fork of his solution, with the most important change in the fork being the addition of the `disabled="disabled"` attribute to the `textarea`. When selecting text within the `textarea` while using that attribute, no caret will appear in the text and the outline will not glow when focus is on the `textarea`. The only other thing to note is that you'll have to control `textarea` browser defaults if you want to obscure the fact that the text is in a `textarea`.