6

I'm a little confused why doesn't this code work!

The HTML Markup:

<div id="diva"><b>Score</b> some <i>goals</i></div>
<div id="soda"></div>

The JavaScript code:

function GetSelectedText () {
if (window.getSelection) {  // all browsers, except IE before version 9
    var range = window.getSelection ();
    alert (range.toString ());
} 
else {
    if (document.selection.createRange) { // Internet Explorer
        var range = document.selection.createRange ();
        alert (range.text);
    }
}
}

var butn = document.getElementById("soda");
butn.onclick = function(){
    GetSelectedText();
}
Develop Smith
  • 146
  • 1
  • 3
  • 13
  • 1
    It's usually better if you explain what is actually happening rather than saying "_this code doesn't work_". I'd receommend looking into [the jQuery Caret plugin](http://www.examplet.buss.hk/jquery/caret.php) – jahroy Jan 27 '13 at 23:32
  • 3
    If you click on anything while a piece of text is highlighted, doesn't that unhighlight it and leave your selection blank? – danronmoon Jan 27 '13 at 23:32
  • you have a space after your toString and other functions - but we need more detail, are you seeing an error or just the wrong behavior? – Dave Jan 27 '13 at 23:33
  • jahroy is right. Use a proper library, jQuery being warmly recommended here. Otherwise, you'll be spending your time learning how the different browsers handle selection. – Mihai Danila Jan 27 '13 at 23:39
  • 1
    @MihaiDanila: A "proper library" will be no help here. The problem is that in some browsers, by the time the button's `click` event fires, the selection has been destroyed. – Tim Down Jan 28 '13 at 00:15
  • @danronmoon: In general yes, but it doesn't happen with actual ` – Tim Down Jan 28 '13 at 00:26
  • "When in doubt throw libraries at it otherwise you might have to learn! Scary thought.." – rlemon Jan 28 '13 at 00:27
  • I mean by saying "doesn't work" that it doesn't do what I'm expecting which is to give me the selected text in HTML format. So when I select "Some" I expect to have this in the alert popup "Score" Sorry if my question was unclear! – Develop Smith Jan 28 '13 at 12:42
  • Possible duplicate of [Get the Highlighted/Selected text](https://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text) – Makyen Dec 07 '17 at 19:23

3 Answers3

11

One problem that you may well be experiencing is that in some browsers (notably IE), by the time the button's click event fires, the selection has been destroyed. You can fix this by using the mousedown event instead (which still allows the selection to be destroyed, but only after the event has been handled), or by making the button unselectable.

I assume your button is not an actual button input, because this behaviour only happens for regular elements.

Demo: http://jsfiddle.net/L9bvU/1/

function GetSelectedText () {
    if (window.getSelection) {  // all browsers, except IE before version 9
        var range = window.getSelection ();
        alert (range.toString ());
    } 
    else {
        if (document.selection.createRange) { // Internet Explorer
            var range = document.selection.createRange ();
            alert (range.text);
        }
    }
}
span {
    background-color: #ccc;
    padding: 3px;
    border: solid gray 1px;
    
}

*[unselectable="on"] {
   -moz-user-select: -moz-none;
   -khtml-user-select: none;
   -webkit-user-select: none;

   /*
     Introduced in IE 10.
     See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
   */
   -ms-user-select: none;
   user-select: none;
}
<div contenteditable="true">Please select some of this text and press a button below</div>

<span onclick="GetSelectedText()">Click</span>
<span onmousedown="GetSelectedText()">Mousedown</span>
<span unselectable="on" onclick="GetSelectedText()">Click, unselectable</span>
Grzegorz Wierzowiecki
  • 10,545
  • 9
  • 50
  • 88
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Yes, you are right but I have another problem which is why I want this code to do. I'm expecting which is to give me the selected text in HTML format. So when I select "Some" I expect to have this in the alert popup "Score" Sorry if my question was unclear! – Develop Smith Jan 28 '13 at 12:57
  • I have found this code and it is very useful but it doesn't work and I don't know why. In the other hand I replaced the "alert (range.text);" with "alert (range.htmlText);" and it works very will in IE but I need the equivalent code to the rest of the browsers, I mean to say "what to replace "alert (range.toString ());" with to make this code work with Mozilla? " – Develop Smith Jan 28 '13 at 13:38
  • @DevelopSmith: What isn't working? Can you make a demo? The function I linked to should just replace your current `GetSelectedText()` function. – Tim Down Jan 28 '13 at 13:44
  • it works the problem was that I mixed both of two functions and it did the mistake. Now everything is OK and I'm very thankful of you. Thank you for helping me. – Develop Smith Jan 28 '13 at 14:26
5
function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection();
    } 
    if (window.document.getSelection) {
        return window.document.getSelection();
    } 
    if (window.document.selection) {
        return window.document.selection.createRange().text;
    }
    return "";  
}
<p onmouseup="getSelectedText(); alert(txt)">
Highlight some of this text
with the mouse select press button end release
to fire the event. </p>


This is my way. You just need to select the text end alert text or anything else.
Does anyone know how OnMouse(event) set for the entire document in html, and it does not have to be directly added to html page.
To be on the other side, as we can change the elements in firebug!>-examples

JohnK
  • 6,865
  • 8
  • 49
  • 75
vlad
  • 313
  • 3
  • 9
  • heyman: You mean that first try change element i firebag, then change it in code – vlad Apr 11 '15 at 03:35
  • @heyman: You mean that first try change element in firebag, then change in code? In such a manner, we know what doing better... – vlad Apr 11 '15 at 03:41
  • I'm not sure what you mean? My edit of the answer just improved the formatting by putting the code within a code block. – heyman Apr 12 '15 at 11:23
  • @heyman I thought because of this sentence: "To be on the other side, as we can change the elements in firebug!>-examples" - what mean? – vlad Apr 12 '15 at 23:02
  • @heyman you said the right thing, sorry.. Yes, I change first in firebag and then in own code! – vlad Oct 19 '15 at 23:42
2

Well there are two problems with the above code. -You can't be guaranteed that

var butn = document.getElementById("soda");

will work because it may execute before the document is done loading

-When you click on another element that's not a button, the selection is lost. If you change the "soda" div to then it will work:

<div id="diva"><b>Score</b> some <i>goals</i></div>
<div id="soda" onclick="GetSelectedText()">This will NOT work</div>
<input type="button" onclick="GetSelectedText()" value="This will work"/>

However I strongly recommend you look at jQuery as the others here have advised; it will make your like a lot easier!

Stephen Byrne
  • 7,400
  • 1
  • 31
  • 51