Skip to content

Instantly share code, notes, and snippets.

@pvdz
Last active August 29, 2015 13:56
Show Gist options
  • Save pvdz/9000941 to your computer and use it in GitHub Desktop.
Save pvdz/9000941 to your computer and use it in GitHub Desktop.
Selection api why you so verbose? :(
function f_rel(el, start, end) {
// end may be < 0 and is relative to start, start must be >=0
f_abs(el, start, start + end);
}
function f_abs(el, start, end){
// end may be 0 < end < start, start must be >=0
var s = getSelection();
s.removeAllRanges();
var r = new Range();
r.setStart(el, 0);
s.addRange(r);
if (typeof start === 'number' && start >= 0) {
if (typeof end === 'number') {
var d = end > start ? 'forward' : 'backward';
end = Math.abs(Math.abs(end) - start); // -5 - 10 = -15, 5 - 10 = -5
} else {
end = 0;
}
} else {
start = 0;
}
// modify api is quite tedious...
while (start--) {
s.modify('move', 'forward', 'character');
}
while (end--) {
s.modify('extend', d, 'character');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment