I'm writing an online book reader. The average book has 270 distinct pages. I'd like the user to be able to browse through the pages but if all are loaded immediately then the page freezes as it's too much content. To fix this I think the best solution is that each page's content is display:none
to begin with and only becomes display:block
when in view.
Unfortunately I'm not very experienced with Javascript and so I'm having difficulty figuring out how to do this.
I'm using only raw Javascript (no JQuery). So far I have this:
https://jsfiddle.net/ya2n8bfm/
<html>
<head>
<style>.bookzone { margin:0; padding:0; overflow:scroll; }</style>
<script>
function scollPos() {
var sp = document.getElementById("bookzone").scrollTop;
if (sp > 100) {
document.getElementById("p2").style.display = "block";
}
}
</script>
</head>
<body>
<div class="bookzone" onscroll="scollPos();">
<div style="width:400;height:400;"><div id="p1" style="display:none;">Page 1</div></div>
<div style="width:400;height:400;"><div id="p2" style="display:none;">Page 2</div></div>
<div style="width:400;height:400;"><div id="p3" style="display:none;">Page 3</div></div>
<div style="width:400;height:400;"><div id="p4" style="display:none;">Page 4</div></div>
<div style="width:400;height:400;"><div id="p5" style="display:none;">Page 5</div></div>
<div style="width:400;height:400;"><div id="p6" style="display:none;">Page 6</div></div>
<div style="width:400;height:400;"><div id="p7" style="display:none;">Page 7</div></div>
<div style="width:400;height:400;"><div id="p8" style="display:none;">Page 8</div></div>
<div style="width:400;height:400;"><div id="p9" style="display:none;">Page 9</div></div>
<div style="width:400;height:400;"><div id="p10" style="display:none;">Page 10</div></div>
<div style="width:400;height:400;"><div id="p11" style="display:none;">Page 11</div></div>
<div style="width:400;height:400;"><div id="p12" style="display:none;">Page 12</div></div>
</div>
</body></html>
That doesn't actually seem to work at all. I'd like that each page becomes display:block
when it's in the viewport (any part of it) and becomes display:none
when it's entirely outside of the viewport.
So my two issues are: (1) what I've done so far doesn't seem to work at all, (2) I'm not sure how to make it know when an element is in the viewport. I could do (2) based on a whole series of rules since every page is the same height, but perhaps there is a more efficient way?