Here's how I solved the issue for my purposes...
I had several scrollable div's (with class txt
), within which the user is allowed to select text — but only within one div at a time (and no other text on the page should be selectable). So, I used css:
*,.noSelect{ user-select:none; }
.txt{ user-select:text; }
...and then listen for the selectstart
event, to grab the ID of the element where selection begins, and immediately disable selection in all the others:
document.addEventListener('selectstart',function(e){
var selStartID=window.getSelection().anchorNode.parentNode.id;
$('.txt').each(function(){
if(this.id!=selStartID){$(this).addClass('noSelect');}
});
});
...then, after you're finished doing whatever you're doing with the selection (copying/saving/etc), you can re-enable selection in all the other elements:
$('.noSelect').removeClass('noSelect');
Coming in CSS4? user-select: contain;
According to Mozilla, CSS UI 4 will simplify this with user-select: contain;
... Currently only supported in IE [Words you don't often hear!]. There's a polyfill on github — though I haven't tried it.
(css-tricks.com has a different opinion about CSS4, and Wikipedia's got another story about it.)