0

I have a div container placed inside an html page. There is some text placed inside it. Now, I want the text (any amount) selected by the user to be displayed in another div container on the same page.

<div id="d1"> Some Random text, Some Random text Some Random text, Some Random text</div>
<div id="d2"></div>

I am stuck on how to extract the text from the d1 container. I have tried using window.getSelection() and related methods. The irony is that it is applied on the entire document. How to go about it?

P.S-JSFiddle demo would be helpful.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user2171262
  • 123
  • 1
  • 2
  • 9
  • 2
    P.P.S. A JSFiddle of what you've tried would be even more helpful – Alexander Mar 14 '13 at 19:10
  • 4
    have a look at this http://mark.koli.ch/2009/09/use-javascript-and-jquery-to-get-user-selected-text.html – mavili Mar 14 '13 at 19:11
  • http://stackoverflow.com/questions/6251937/how-to-get-selecteduser-highlighted-text-in-contenteditable-element-and-replac – Dom Mar 14 '13 at 19:12
  • Yes, I have looked into it. But, they have used methods (that are defined on the document object of JS: https://developer.mozilla.org/en-US/docs/DOM/document.getSelection ) that apply on the entire document. I just want to restrict it to the the div content only and not the entire page. – user2171262 Mar 14 '13 at 19:16
  • Try this, http://stackoverflow.com/questions/1173194/select-all-div-text-with-single-mouse-click – Shouvik Mar 14 '13 at 19:20
  • http://stackoverflow.com/questions/1173194/select-all-div-text-with-single-mouse-click is not working well on double-clicking or clicking the text. It works only when the user gently presses the left mouse button and selects some content. – user2171262 Mar 14 '13 at 19:41

1 Answers1

0

Tried this on my mac seems to be working on Safari/Chrome and FF not sure about IE though

<head>
    <script>
        var mouseup_fun = function()
        {
            var str = document.getSelection().toString();
            if (str.length > 0) {
                document.getElementById("div2").innerHTML = str;  
            }

        }
    </script>
</head>
<body >
    <div id="div1" onmouseup="mouseup_fun()">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </div>
    </br></br>
    <div id="div2">

    </div>
</body>
</html>
Raghu
  • 94
  • 3