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);
}

Answer by Starx

There is no dependable way to ensure this. However selection can be prevent on modern browsers using no-select.

#div1, #div2 {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

[Source]

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!