Ryan Brackett
Ryan Brackett

Reputation: 1022

Using Parent Scrollbar to scroll iFrame

I want to use the parent scroll-bar to scroll a tall iframe.

The problem: I need the bars to move in terms of percentage instead of per pixel. That would allow both bars to touch the bottom at the same time.

$(document).scroll(function () {
    var scrollTop = $(window).scrollTop();
    var docHeight = $(document).height();
    var winHeight = $(window).height();
    var scrollPercent = (scrollTop) / (docHeight - winHeight);
    var scrollPercentRounded = Math.round(scrollPercent * 100);

    var divscrollTop = $(window).scrollTop();
    var divdocHeight = $(document).height();
    var divwinHeight = $(window).height();
    var divscrollPercent = (divscrollTop) / (divdocHeight - divwinHeight);
    var divscrollPercentRounded = Math.round(divscrollPercent * 100);

    $('div').scrollTop((scrollPercentRounded * divscrollPercentRounded));

});

Working example http://jsfiddle.net/RyanBrackett/xcw1yokm/

Upvotes: 2

Views: 5906

Answers (2)

Bruce
Bruce

Reputation: 1071

I no this is an old question, but one could also just disable the parent scrollbar and allow the iframe to be the main scrollbar. Of course this only works if you can set width 100% or 100vw.

In such a case one can instead just set the margin of all elements to 0px and overflow to hidden on containing parent.

Then set iframe to 100 vw and (optionally) 100 vh

The iframe is then 100% controlled by the parent containing scrollbar as seen below:

    <style>
        * { margin:0px; }
        body {overflow:hidden;}
    </style>
<iframe src="https://network.tactokens.com" style="min-width:100vw; min-height:100vh;">

Upvotes: 2

Ren&#233; Truelsen
Ren&#233; Truelsen

Reputation: 11

I just found this post and spend a few minutes playing with the code to make it work. Here's a my version of the coffee-script-code:

$(window).load(function(){
       $(document).scroll(function () {
        var scrollTop = $(window).scrollTop();
        var docHeight = $(document).height();
        var winHeight = $(window).height();
        var scrollPercent = scrollTop / (docHeight - winHeight);

        var divHeight = $("div").height(); 
        var divContentHeight = $('div')[0].scrollHeight;

        var equation = scrollPercent * (divContentHeight-divHeight);

        $('div').scrollTop(equation);

    });

}); 

/ René

Upvotes: 1

Related Questions