Find element's position in browser scroll
var note = document.getElementsByName('Note')[0];
var screenPosition = note.getBoundingClientRect();
The ClientRect returned by getBoundingClientRect()
has values for .top
, .left
, .right
, .bottom
, .width
, and .height
.
These are pixel positions on the visible window; as you scroll the page the .top
and .bottom
values will change, and may even become negative as the item scrolls off the top of the view.
Note that—unlike the solution accumulating offsetLeft
/offsetTop
—this solution properly accounts for borders and padding on the body
and html
elements in all browsers (Firefox).
See this test case: http://jsfiddle.net/QxYDe/4/ (scroll the page and watch the values change).
Also supported by Internet Explorer.
My guess is that you need the note to stay fixed to the top left corner at all times? Even when scrolled?
You can do this with CSS only! :)
HTML:
<div id="Note" name="Note">Example</div>
CSS:
div #Note {
background-color:rgb(255,255,204)
left: 0px;
position: absolute;
top: 0px;
z-index: 999;
}
@media screen {
body > div #Note {
position: fixed;
}
}
EDIT: With several notes (not tested):
HTML:
<div id="Note1">Example</div>
<div id="Note2">Example</div>
<div id="Note3">Example</div>
<div id="Note4">Example</div>
CSS:
div #Note1 {
background-color:rgb(255,255,204)
left: 0px;
height: 20px;
position: absolute;
top: 0px;
z-index: 999;
}
div #Note2 {
background-color:rgb(255,255,204)
left: 0px;
height: 20px;
position: absolute;
top: 20px;
z-index: 999;
}
div #Note3 {
background-color:rgb(255,255,204)
left: 0px;
height: 20px;
position: absolute;
top: 40px;
z-index: 999;
}
div #Note4 {
background-color:rgb(255,255,204)
left: 0px;
height: 20px;
position: absolute;
top: 60px;
z-index: 999;
}
@media screen {
body > div #Note1 {
position: fixed;
}
body > div #Note2 {
position: fixed;
}
body > div #Note3 {
position: fixed;
}
body > div #Note4 {
position: fixed;
}
}
function position(elem) {
var left = 0,
top = 0;
do {
left += elem.offsetLeft-elem.scrollLeft;
top += elem.offsetTop-elem.scrollTop;
} while ( elem = elem.offsetParent );
return [ left, top ];
}
var elem = document.getElementById('id');
position(elem);
Subtract the scroll positions.