I have this script that captures the selected text, I would like to only do something when the selecting of text ends, not while the selection is in progress, the browser is IE9 only.
The text can also be selected by double-clicking on a word in which case the function also should do something once, when I use onMouseUp
this is twice.
<head>
<script type="text/javascript">
function selectedText(){
var doc = document.selection;
if(doc && doc.createRange().text.length != 0){
log.innerHTML = doc.createRange().text;
}
}
</script>
</head>
<body onselect="selectedText();">
<span id=sp>this is the text from where you can select one or more words</span>
<div id=log style="background-color=yellow;"></div>
</body>
Never mind, figured it out, this is for future reference
<head>
<script type="text/javascript">
count = 0;
function selectedText(){
var doc = document.selection;
if(doc && doc.createRange().text.length != 0){
count++;
log.innerHTML = "count: "+count+" "+doc.createRange().text;
}
}
function AddEventHandler () {
var sp = document.getElementById ("sp");
if (sp.addEventListener) { // all browsers except IE before version 9
sp.addEventListener ("click", selectedText, false);
}
else {
if (sp.attachEvent) { // IE before version 9
sp.attachEvent ('onmouseup', selectedText);
}
}
};
</script>
</head>
<body onload=AddEventHandler()>
<span id=sp>this is the text from where you can select one or more words</span>
<div id=log style="background-color=yellow;"></div>
</body>
or this shorter version
<head>
<script type="text/javascript">
count = 0;
document.onselectionchange = function() {
count++;
var sel = window.getSelection();
if (sel.rangeCount > 0) {
var range = sel.getRangeAt(0);
document.getElementById("log") = count+":"+range.toString();
}
};
</script>
</head>
<body>
<span id=sp>this is the text from where you can select one or more words</span>
<div id=log style="background-color=yellow;"></div>
</body>