Wednesday 15 May 2013

javascript - Bootstrap 3 scrollspy - detect scroll on div -



javascript - Bootstrap 3 scrollspy - detect scroll on div -

i want utilize scrollspy it's not designed for, yet may job.

i have div #mytarget , want observe when scrolled top of .container , each time 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 target!'); });

here jsfiddle link

p.s. know can utilize other plugins such e.g. jquery waypoints stick bootstrap if possible.

as per bootstrap 3 documentation:

when scrollspying on elements other , sure have height set , overflow-y: scroll; applied.

once sure scrollspy working, utilize jquery code observe if on top:

$('#myscrollspy').on('activate.bs.scrollspy', function () { var activesection = $(this).find("li.active a").attr("href"); if(activesection === "#section1") { alert("i have reached top."); } });

its pretty self-explanatory. bind event activate.bs.scrollspy , whenever executes go , fetch href of current selected item. check if href item first item defined in html. if yes, on top.

check working jsfiddle example.

whenever scroll downwards , 1 time again come up, alert box show letting know have reached top.

javascript jquery twitter-bootstrap twitter-bootstrap-3 scrollspy

No comments:

Post a Comment