After encountering a problem, I devised a solution that worked well for my needs...
I had multiple scrollable divs (with the class txt
) where users could select text, but only within one div at a time (while preventing selection in other parts of the page). To achieve this, I utilized CSS:
*,.noSelect{ user-select:none; }
.txt{ user-select:text; }
...and then monitored the selectstart
event to identify the element where the selection began and promptly disable selection in all other divs:
document.addEventListener('selectstart',function(e){
var selStartID=window.getSelection().anchorNode.parentNode.id;
$('.txt').each(function(){
if(this.id!=selStartID){$(this).addClass('noSelect');}
});
});
Once the user finished interacting with the selection (copying/saving/etc), selection was re-enabled in all other elements:
$('.noSelect').removeClass('noSelect');
Anticipating user-select: contain;
in CSS4
Mozilla suggests that CSS UI 4 will introduce a simpler solution with user-select: contain;
... Currently, only IE supports this [A rare occurrence!]. A polyfill on github is available — although I have not personally tried it.
(css-tricks.com and Wikipedia provide differing perspectives on CSS4, with additional insights found elsewhere.)