Essentially, the idea is to handle the event document.onmouseupappropriately, show the hidden “accelerator”, divand extract the selected text.
I think the following sample will be a good starting point for you:
<html>
<head>
<script>
function getSelectedText() {
var selection = '';
if (window.getSelection) selection = window.getSelection().toString();
else if (document.getSelection) selection = document.getSelection();
else if (document.selection) selection = document.selection.createRange().text;
return selection;
}
function showAccelerator(x, y){
var text = getSelectedText();
if (text !== ''){
accelerator.style.display = '';
accelerator.style.left = x;
accelerator.style.top = y;
timeout_id = setTimeout(hideAccelerator, 1000);
} else {
hideAccelerator()
}
}
function hideAccelerator(){
clearTimeout(timeout_id);
accelerator.style.display='none';
}
function isAcceleratorHidden(){
return accelerator.style.display === 'none';
}
function onMouseUp(evt){
if (isAcceleratorHidden()){
var event2 = (document.all) ? window.event : evt;
showAccelerator(event2.clientX, event2.clientY);
}
}
function alertSelection(){
alert(getSelectedText());
}
document.onmouseup = onMouseUp;
</script>
</head>
<body>
<div id="accelerator" style="position: absolute; width: 100px; left: 0px; top: -50px; display: none; border: solid; background-color : #ccc;">
accelerator div<input type="button" value="alert" onclick="alertSelection();" />
</div>
<p>
sometext<br/><br/><br/>
even more text
</p>
</body>
</html>
source
share