Monday, May 20, 2024
151
rated 0 times [  155] [ 4]  / answers: 1 / hits: 24157  / 12 Years ago, sun, january 27, 2013, 12:00:00

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

More From » getselection

 Answers
38

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>




[#80589] Friday, January 25, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tristab

Total Points: 735
Total Questions: 106
Total Answers: 96

Location: Grenada
Member since Sun, Dec 20, 2020
3 Years ago
tristab questions
Sat, Sep 25, 21, 00:00, 3 Years ago
Sun, Jan 31, 21, 00:00, 3 Years ago
Wed, Dec 2, 20, 00:00, 4 Years ago
Fri, Oct 23, 20, 00:00, 4 Years ago
;