Search code examples
javascriptjquerytwitter-bootstraptwitter-bootstrap-3scrollspy

Bootstrap 3 scrollspy - detect scroll on div


I want to use the scrollspy to do something it's not necessarily designed for, yet it may do the job.

I have a div #myTarget and I simply want to detect when it scrolled to the top of the .container and do something each time it does so.

HTML:

<div class="container" data-spy="scroll" data-target="#myTarget">
    <div class="row">
        <div class="col-md-12 some-content">.some content</div>
    </div>
    <div class="row">
        <div class="col-md-12" id="myTarget">#myTarget</div>
    </div>
</div>

JS:

$('body').scrollspy({
    target: '#myTarget'
});

$('#myTarget').on('activate.bs.scrollspy', function () {
    console.log('got to the target!');
});

Here is a jsfiddle link

P.S. I know I can use other plugins such e.g. jQuery Waypoints but I would like to stick just to Bootstrap if possible.


Solution

  • As per bootstrap 3 documentation:

    When scrollspying on elements other than the <body>, be sure to have a height set and overflow-y: scroll; applied.

    Once you are sure that your scrollspy is working, use this jquery code to detect if you are on top:

    $('#myScrollspy').on('activate.bs.scrollspy', function () {
       var activeSection = $(this).find("li.active a").attr("href");
    
       if(activeSection === "#section1")
       {
           alert("I have reached to the top.");
       }
    });
    

    You bind with the event activate.bs.scrollspy and whenever it executes you go and fetch the href of the current selected item. Then you check if that href item is the first item defined in your html. If yes, then you are on top.

    Check my working JSFIDDLE example.

    Whenever you scroll down and again come back up, the alert box will show up letting you know that you have reached to the top.