I have two simple JavaScript functions: getSelectedText()
and doSomethingWithSelectedText()
that I found in a different example.
Now I've adjusted it more to my needs: http://jsfiddle.net/83T7U/.
The example currently works but not the way it should. Currently, when text is selected, there is an alert()
, but instead the text on button should change from Reply to Quote.
So, instead:
alert("Text selected - it should change "Reply" to "Quote" text button ONLY if text was selected within one of these DIVs and text should change only in the div within which the text was selected.");
It should be like document.getElementsByTagName("button")
or similar.
My goal is to:
Change the value of the button from Reply to Quote as soon as text from a particular
div
is selected. When the text is de-selected, then button should change back to Reply.Make sure the Reply<>Quote change applies only when text is selected within one of these DIVS (and not in other parts of the page).
Minimize the functions - I think instead of the two functions one is enough because I don't want to know the value of selection - I just want to check if there is something (ie. at least one character) selected/highlighted.
The JavaScript should work correctly with all the major browsers.
Please note I cannot use jQuery here. Thank you!
HTML:
<div id="first" style="background:yellow">DIV1: First some test text for you to select
<br>
<button>Reply</button>
</div>
<br>
<div id="second" style="background:green">DIV2: Second some test text for you to select
<br>
<button>Reply</button>
</div>
<br>
<div id="third" style="background:lightblue">DIV3: Third some test text for you to select
<br>
<button>Reply</button>
</div>
<br>
<i>(there could be more similar divs on a page)</i>
JavaScript:
function getSelectedText() {
var text = "";
if (typeof window.getSelection != "undefined") {
text = window.getSelection().toString();
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
text = document.selection.createRange().text;
}
return text;
}
function doSomethingWithSelectedText() {
var selectedText = getSelectedText();
if (selectedText) {
alert("Text selected - it should change Reply to Quote text button ONLY if text was selected within one of these DIVs and text should change only in the div within which the text was selected.");
}
}
document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;