September 18, 2012
Prevent multiple selection of a div
Question by user1551056
I have multiple divs on my page.I want to copy selected text from div1 to div2 only.Selection on div2, div3, div4 should not get copied. If ctrl+A is pressed or multiple divs are selected at a time, copy should not happen.
//Validation for including text only from specified div
$('#DocumentText').mouseup(function (e) {
debugger;
isSelected = true;
flaginclude = 1;
// e.stopPropagation();
});
$(document).mouseup(function (e) {
debugger;
if (flaginclude != 1) {
e.stopImmediatePropagation();
isSelected = false;
}
flaginclude = 0;
});
myfunction()
{
if(isSelected)
{
//logic to append selected text on div2
}
}
Answer by Tim Down
You can alter the selection after the event to be limited to just a particular element. Here’s an example of how to get just text selected within a particular element:
http://stackoverflow.com/a/5801903/96100
Here’s an example function that uses my Rangy library to limit a selection:
Live demo: http://jsfiddle.net/nm3FM/
Code:
function limitSelectionToElement(el) {
var selectedRange = null;
var sel = rangy.getSelection();
var elRange = rangy.createRange();
elRange.selectNodeContents(el);
if (sel.rangeCount) {
selectedRange = sel.getRangeAt(0).intersection(elRange);
}
elRange.detach();
sel.setSingleRange(selectedRange);
}