Reputation:
I was fiddling around on a jsfiddle and I discovered a potential issue. Within the fiddle, I have a logger setup to track the position of the scroll if the site is embedded in a iframe (which it is on jsfiddle). However, I need to be able to detect with javascript which value I used would be appropriate for tracking scroll position within an iframe across all browsers. I used the values:
window.scrollTop
document.documentElement.scrollTop
document.body.scrollTop
The fiddle's js:
window.addEventListener("scroll",
function() {
console.log(
"window:" + window.scrollTop +
"; documentElement:" + document.documentElement.scrollTop +
"; body:"+ document.body.scrollTop
);
}
);
The fiddle's CSS:
html{ height : 300% }
Using Chrome, I get logs that are similar to:
window:undefined; documentElement:0 (always 0); body:[some number] (variable number-actual scroll)
NOTE: in response to charlieftl's comments I need to make a script that will detect which of the three values I listed is appropriate for tracking the scroll position.
Also, the purpose of the script is to get the appropriate scroll position based upon whether the website is iframed(embedded) or not. When it is not the appropriate value is window.scrollTop, but inside an iframe it seems to be document.body.scrollTop. Also, I need to know when it is appropriate to use document.documentElement.scrollTop.
NOTE: jQuery solutions are appreciated, but native javascript is preferred.
Upvotes: 2
Views: 101
Reputation: 40
Because I am nice, I went and tested this fiddle on several browsers (except Opera-for what ever reason I can't download it).
I found that your script logs a value for document.documentElement.scrollTop
when it is in IE and Firefox. While in Chrome, it logs the value for body.scrollTop
. IE, Chrome, and Firefox all log undefined
for the window.scrollTop
value.
Therefore, window.scrollTop is useless for the iframed content. But just for the sake of the case that this is not true in Opera, I made this code:
window.scrollTo(0,20);
document.documentElement.scrollTo(0,20);
document.body.scrollTo(0,20);
/* ^^these scroll values are only temporary */
if(isset(window.scrollTop) && window.scrollTop=20)
alert("use window as object");
if(isset(document.documentElement.scrollTop) && document.documentElement.scrollTop=20)
alert("use documentElement as object");
if(isset(document.body.scrollTop) && document.body.scrollTop=20)
alert("use documentElement as object");
window.scrollTo(0,0);
document.documentElement.scrollTo(0,0);
document.body.scrollTo(0,0);
/* ^^default the scroll value back to normal state */
NOTE: However, I would be wary of using window, because it may be actually referencing the parent window and not the iframe -don't quote me on this. I am not very familiar with iframes, I was just playing around with your fiddle
Upvotes: 2