Hi,
I am trying to get the y coordinate of the cursor within a contenteditable div using getBoundingClientRect(). The IE branch of the code works, but the other branch (i.e. Firefox 3.5 for my current testing purposes) does not.
The code below has the problematic lines marked with * in the comment. At that point in the code, both selObj and selRange have a value (confirmed in Firebug), but I cannot call getBoundingClientRect() on either of them (gives e.g. selObj.getBoundingClientRect is not a function). I have read that getBoundingClientRect() is now supported on Firefox on the Range object, but I can't get it to work. I guess I must be calling it on the wrong type of object...? What should I be calling it on ?
The following code is the full test case as an html file containing the relevant javascript. Viewed in IE, I get a value for the y coordinate of the cursor, but in Firefox it pops.
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
#pageContainer {
padding:50px;
}
.pageCommon {
width: 100px;
height: 100px;
background-color:#ffffD0;
padding: 10px;
border: 1px solid black;
overflow: auto;
}
</style>
</head>
<body>
<div id="pageContainer">
<div id="editor" class="pageCommon" contenteditable onclick="setPageNav();" onkeypress="setPageNav();">
</div>
<div>y: <span id="y"></span></div>
</div>
<script>
var y;
function setPageNav() {
page = document.getElementById("editor");
if (window.getSelection) {
var selObj = window.getSelection();
var selRange = selObj.getRangeAt(0);
// *** Neither of these next two lines work, error is : selObj.getBoundingClientRect is not a function
y = selObj.getBoundingClientRect().top;
y = selRange.getBoundingClientRect().top;
} else if (document.selection) {
var range = document.selection.createRange();
y = range.getBoundingClientRect().top;
}
document.getElementById("y").innerHTML = y;
}
</script>
</body>
</html>