Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Test Page</title>
<style>
  body {
    font-family: sans-serif;
  }
  #target {
    border: 1px solid black;
  }
</style>
</head>
<body>
  <button onClick="javascript:snapSelectionToWord();">Snap</button>
<div contenteditable="true" onmouseup="snapSelectionToWord()">
    This is a demo text for a student.
</div>
</body>
</html>
 
function snapSelectionToWord() {
    var sel;
    
    // Check for existence of window.getSelection() and that it has a
    // modify() method. IE 9 has both selection APIs but no modify() method.
    if (window.getSelection && (sel = window.getSelection()).modify) {
        //debugger;
        sel = window.getSelection();
        if (!sel.isCollapsed) {
            // Detect if selection is backwards
            var range = document.createRange();
            range.setStart(sel.anchorNode, sel.anchorOffset);
            range.setEnd(sel.focusNode, sel.focusOffset);
            var backwards = range.collapsed;
            range.detach();
            // modify() works on the focus of the selection
            var endNode = sel.focusNode, endOffset = sel.focusOffset;
            sel.collapse(sel.anchorNode, sel.anchorOffset);
            if (backwards) {
                sel.modify("move", "backward", "character");
                sel.modify("move", "forward", "word");
                sel.extend(endNode, endOffset);
                console.log("BackWords"+sel.anchorOffset+"and "+sel.focusOffset);
                var startObj = sel.anchorOffset;
                var endObj = sel.focusOffset;
                alert(startObj+"_"+endObj);
                
                sel.modify("extend", "forward", "character");
                sel.modify("extend", "backward", "word");
            } else {
                sel.modify("move", "forward", "character");
                sel.modify("move", "backward", "word");
                sel.extend(endNode, endOffset);
                sel.modify("extend", "backward", "character");
                sel.modify("extend", "forward", "word");
                console.log("Forwards"+sel.anchorOffset+"and "+sel.focusOffset);
            }
        }
    } else if ( (sel = document.selection) && sel.type != "Control") {
        var textRange = sel.createRange();
        if (textRange.text) {
            textRange.expand("word");
            // Move the end back to not include the word's trailing space(s),
            // if necessary
            while (/\s$/.test(textRange.text)) {
                textRange.moveEnd("character", -1);
            }
            textRange.select();
        }
    }
}
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers