This example shows how to speak any User Selected Text when they complete highlighting(mouseup).
Try this anywhere on this website. Go ahead, highlight this sentence.![]()
This is example code to add just before the closing body tag.
<script>
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
// for Internet Explorer 8 and below. For Blogger, you should use && instead of &&.
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
$(document).ready(function (){ // when the document has completed loading
$(document).mouseup(function (e){ // attach the mouseup event for all div and pre tags
setTimeout(function() { // When clicking on a highlighted area, the value stays highlighted until after the mouseup event, and would therefore stil be captured by getSelection. This micro-timeout solves the issue.
responsiveVoice.cancel(); // stop anything currently being spoken
responsiveVoice.speak(getSelectionText()); //speak the text as returned by getSelectionText
}, 1);
});
});
</script>
Keywords: text selection, highlighted text, selected text