I've got an editor in a contentEditable
div
inside a Windows Store
app WebView
, and because of quirks in contentEditable
handling of PageUp / PageDown
I've had to implement my own Page Up / Page Down
by trapping the key down
event in Javascript
and scrolling the page up or down by one screen height.
The trouble is, the cursor does not move when paging, as it should. When the user presses the cursor keys the page scrolls back to where it was before pressing Page Up / Page Down
Here's the code I'm using the catch the key down events
$(window).bind('keydown', function (event) {
if (event.which == 33) {
// page up
event.preventDefault();
// scroll page to current scroll - window height
$(document).scrollTop($(document).scrollTop() - document.body.clientHeight);
// place cursor on page
}
else if (event.which == 34) {
// page down
event.preventDefault();
// scroll page to current scroll + window height
$(document).scrollTop($(document).scrollTop() + document.body.clientHeight);
// move cursor to bottom
}
});
I can set the caret position using this function
// 'editor' is a reference to my contentEditable div
function setCaretPosition(cPos) {
var charIndex = 0, range = document.createRange();
range.setStart(editor, 0);
range.collapse(true);
var nodeStack = [editor], node, foundStart = false, stop = false;
while (!stop && (node = nodeStack.pop())) {
if (node.nodeType == 3) {
var nextCharIndex = charIndex + node.length;
if (!foundStart && cPos >= charIndex && cPos <= nextCharIndex) {
range.setStart(node, cPos - charIndex);
foundStart = true;
}
if (foundStart && cPos >= charIndex && cPos <= nextCharIndex) {
range.setEnd(node, cPos - charIndex);
stop = true;
}
charIndex = nextCharIndex;
} else {
var i = node.childNodes.length;
while (i--) {
nodeStack.push(node.childNodes[i]);
}
}
}
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
But how do I know where to set it? I can infer the text height from a given position by truncating the text after the cursor and then measuring the height of the div, but I don't know how to do the reverse.
Update
I'm looking for any solution which will allow the Page Up / Page Down keys to function as normal within a contentEditable div, in a WebView, in a Windows Store App.
Definition of "Normal": With the cursor at the top of a long, contentEditable document, pressing Page Down
should scroll the div down by the height of that div, and move the cursor the same amount. Page Up
should obviously do the opposite, scrolling up the way.
This is apparently not how Page Up
/ Page Down
work on a Mac, but I'm not interested in that as this is a Windows Store app.
NOTE: I am not looking for a function to set the caret position. I already have that.
FYI: I find it is adequate to test in IE11 in desktop mode. This uses the same rendering / javascript engine as the Windows Store WebView.