Using the main scrollbar to scroll an iframe
by
, 01-20-2015 at 03:45 PM (50529 Views)
If we want to use the browser's scrollbar to scroll the content of an iframe, we must do the following:
- calculate iframe's offsetHeight + pixel distance of top of iframe with respect to top of main window + pixel distance of bottom of iframe with respect to bottom of main window ;
- give the main window a pixel height that is identical to the result of that calculation;
- make sure that the value for the number of pixels that the content of the iframe is scrolled upward (in the case of an overflow) is 'known' by the main window.
As implied by the use of the term 'pixels', the top and bottom values for the iframe should be given in pixels. The iframe must have position: fixed. Example:
So how do we apply (1), (2) and (3) above to the above iframe and to the main window? (1) and (2) can be achieved by giving the div containing the iframe a ID, by giving the iframe a name and then adding the following onload to the iframe:Code:<div style="position: fixed; left: 10%; top: 80px; right: 10%; bottom: 65px; background: white; "> <iframe style="position: absolute; height:100%; width:100%;" src="some_file.html" > </iframe> </div>
We now have an iframe with a functioning scrollbar and a main window with a non-functioning one. To get rid of the iframe's scrollbar, we simply put scrolling="no" inside the iframe tag. To force the main window's scrollbar to function properly, we use the following script (in the main window), which meets the requirement of (3) above:Code:<div id="iframe_container" style="position: fixed; left: 10%; top: 80px; right: 10%; bottom: 65px; background: white; "> <iframe name="ifr" style="position: absolute; height:100%; width:100%;" src="some_file.html" onload = "document.body.style.height = frames.ifr.document.body.offsetHeight + parseInt(document.getElementById('iframe_container').style.top) + parseInt(document.getElementById('iframe_container').style.bottom) + 'px'" > </iframe> </div>
We're not done yet. If the iframe's content is a lot more than just text, the height of the main window's scrollbar may not adjust to changements due to window resizing. In order to ensure that everything continues to work well after the (main) window has been resized, we should add the following script to the main window:Code:<script> window.onscroll = function() { frames.ifr.document.documentElement.scrollTop = window.pageYOffset; frames.ifr.document.body.scrollTop = window.pageYOffset; // Google Chrome, Safari, documents without valid doctype } </script>
More explanations and demo here.Code:<script> window.onresize=function() { document.body.style.height = frames.ifr.document.body.offsetHeight + parseInt(document.getElementById('iframe_container').style.top) + parseInt(document.getElementById('iframe_container').style.bottom) + 'px' } </script>