4
votes

I have a page with many tables and divs. And one of them with some text. Also page have a url after this div.

Needed: - if user select text from div id = "comment" (text inside div and inside another div into this div), then after press url get alert with this text only (without tags). - if user select text not from div (text not inside div) - do nothing.

I've already tryed to make another DIVs and Tables in page unselectable with CSS (-moz-user-select: -moz-none;-khtml-user-select: none;-webkit-user-select: none;-o-user-select: none;user-select: none;" but this not way what i'm searching for... Needed javascript.

<html>
<head><title>1</title></head>
<body>
    <script type="text/javascript">

        function getSelectedval(){

            var txt = '';
            if (window.getSelection) {
                txt = window.getSelection();
            } else if (document.getSelection) {
                txt = document.getSelection();
            } else if (document.selection) {
                txt = document.selection.createRange().text;
            }
            alert(txt);
        }
    </script>

    <div>hello my friend</div>
    <br/>
    <div id="comment">here is just a some text for testing <div id="text"><strong>this div inside div</strong></div> this selected value</div>
    <a href="javascript:getSelectedval()">url</a>
</body>
</html>

Thanks

1

1 Answers

3
votes
function select() {

var flag = 0;
sel = window.getSelection();
for (var i = 0; i < sel.rangeCount; i++) {
    var s = sel.getRangeAt(i).startContainer.parentNode.id;
    var e = sel.getRangeAt(i).endContainer.parentNode.id;
    if (s == "a") flag = 1;
    if (flag = 1 && e == "a" || e == "child") flag = 2;
}

if (flag == 2) alert(sel);

}

document.getElementById("btn").addEventListener("click", function () {
select();
});

http://jsfiddle.net/gRYQR/2/