"Floating" sidebar within an element when scrolling

6

I have a layout Bootstrap with a sidebar on the right and I need it to "rotate" (up / down) when doing scroll , but not on top of the header and footer. that just "floats" within div[role=main]

My layout:

Mycode:

<headerclass="container">
    <div class="row">
        <div class="col-sm-12">Header</div>
    </div>
</header>

<div role="main" class="container">
    <div class="row">
        <div class="col-sm-8 col-lg-9">
            Main Content
        </div>

        <aside class="col-sm-4 col-lg-3">
            <section class="budget-summary">
                <h2 class="text-center">Resumo</h2>                
            </section>
        </aside>
    </div>
</div>

<footer>
    <div class="row">
        <div class="col-sm-12">Footer</div>
    </div>
</footer>

EDIT:

I got the bar to run with the bootstrap affix plugin:

$('.budget-summary').affix({
    offset: {
        top: 0,
        bottom: function () {
            return (this.bottom = $('footer#page-footer').outerHeight(true));
        }
    }
});

However, a problem has now arisen. The contents of the sidebar are dynamic (grows and shrinks). which sometimes causes the contents of the sidebar not to be shown in full, as the following figure shows:

Is there a way around this?

    
asked by anonymous 15.12.2014 / 04:28

2 answers

2

One of Bootstrap's features does exactly what you want, the affix . the only requirement is to add a style position: absolute to the element you want to set and run a JS code to initialize the behavior.

link

    
15.12.2014 / 12:46
6

You will need to use JavaScript to read the scrollbar and change the position of this sidebar.

A suggestion (using jQuery as I assume using Bootstrap has jQuery) is:

var main = $('div[role=main]').outerHeight();
var posicaoFooter = $('footer').offset().top;
var sidebarDiv = $('aside');

$(window).on('scroll', function () {
    var scroll = $(this).scrollTop();
    if (scroll + sidebarDiv.outerHeight() < main) sidebarDiv.css('margin-top', scroll);
});

Example: link

In this code when the scroll happens it will compare the value of the scroll + height of the sidebar and will change the position while that value together is smaller than the total height of main . Maybe it needs CSS tuning but I think it's this idea you need and you can see in the example how it works.

    
15.12.2014 / 10:31