RobM
RobM

Reputation: 432

Is it possible to limit text selection to current element?

<div class="container">
<div class="item1">text text text in div 1</div>
<div class="item2">text text text in div 2</div>
</div>

Is it possible (by any HTML node, CSS or JS) to prevent from selecting text in div.item2 if selection started from text in div.item1 and the other way around - starting from div.item2 and limit to it (prevent item1 form being selected)?

Upvotes: 6

Views: 2062

Answers (4)

ashleedawg
ashleedawg

Reputation: 21639

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.)

Upvotes: 1

HaveSpacesuit
HaveSpacesuit

Reputation: 4004

The user-select: contain option does this. Unfortunately, it is only supported by ... IE???

https://developer.mozilla.org/en-US/docs/Web/CSS/user-select#browser_compatibility

Upvotes: 1

easeccy
easeccy

Reputation: 5086

Easiest way is using CSS:

.item1 {
  user-select: none;
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  -o-user-select: none;
}
<div class="item1"> Unselectable text</div>
<div class="item2"> Selectable text</div>

Upvotes: -2

Jeremy Thille
Jeremy Thille

Reputation: 26390

I came up with this, with a bit of jQuery code :

let $items = $(".item")

$items
	.mousedown( function() {
		$(this).siblings().css({ "user-select" : "none" , color : "lightgrey"})	
	})
	.mouseup( function() {
		$items.css({ "user-select" : "auto" , color : "black"})	
	})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
	<div class="item">text text text in div 1</div>
	<div class="item">text text text in div 2</div>
	<div class="item">text text text in div 3</div>
	<div class="item">text text text in div 4</div>
</div>

Upvotes: 3

Related Questions