SO: Henrik Petterson 01-16
Selecting whole words in text node without wrapping in elements
HTML
<p class="drag">
Hello world, Attack on Titan season two!
</p>
<p class="drag">
Hello world, Attack on Titan season two!
</p>
<div class='testDiv'>
</div>
CSS
.testDiv {
/* position: absolute; */
height: 100px;
width: 100px;
background-color: red;
}
JavaScript
var WordJumpSelection = (function() {
var watchList = [];
var WordJumpSelection = {
stopWatching: function(elem) {
var wlIdx = watchList.indexOf(elem);
if(wlIdx > -1) watchList.splice(wlIdx,1);
},
watch: function(elem) {
var elems = Array.prototype.slice.call(typeof elem.length === "number" ? elem : arguments);
if(watchList.length === 0)
{
WordJumpSelection.init();
}
elems.forEach(function(elem) {
if(watchList.indexOf(elem) === -1)
{
watchList.push(elem);
}
});
},
init: function() {
function handleSelectionChange() {
if(watchList.length === 0) return;
var selection = window.getSelection();
//if(selection.toString().length === 0) return;
var selDir = getSelectionDir(selection);
var startNode,endNode,startPos,endPos;
if(selDir === 1)
{
startNode = selection.anchorNode;
endNode = selection.focusNode;
startPos = selection.anchorOffset;
endPos = selection.focusOffset;
}
else
{
startNode = selection.focusNode;
endNode = selection.anchorNode;
startPos = selection.focusOffset;
endPos = selection.anchorOffset;
}
var rangeStart = textNodeIsWatched(startNode) ? roundSelectionIndex(startNode,0,startPos) : startPos-1;
var rangeEnd = textNodeIsWatched(endNode) ? roundSelectionIndex(endNode,1,endPos) : endPos;
var r = document.createRange();
// r.setStart(startNode,rangeStart+1)
// r.setEnd(endNode,rangeEnd)
r.selectNode(document.querySelector('.testDiv'))
selection.removeAllRanges();
selection.addRange(r);
}
document.documentElement.addEventListener('mouseup', handleSelectionChange);
document.documentElement.addEventListener('keyup', function(e) {
if(e.keyCode === 16)
{
handleSelectionChange();
}
});
WordJumpSelection.init = function(){};
}
};
return WordJumpSelection;
function getSelectionDir(sel) {
var range =...