javascript - How to make an element scroll when scrolling body -
when mousewheel scrolled on body of page event can captured. i'd event trigger target element scroll.
#target scrollable element never height of page. i'd capture mousescroll event anywhere on page if cursor not on element element still scrolls.
var mycounter = 0; // capture scroll event on body $( 'body' ).on( 'dommousescroll mousewheel', function () { // todo: scroll #target instead of body });
thanks post showing me how capture scroll wheel events: capturing scroll wheel events
you can have @ this.
js
$(function () { var mycounter = 0, myothercounter = 0; var scroll = 0; $("#target").scroll(function () { mycounter = mycounter + 1; $("#log").html("<div>handler .scroll() called " + mycounter + " times.</div>"); }); //firefox // $(document).bind(...) works $('#body').bind('dommousescroll', function (e) { if (e.originalevent.detail > 0) { scrolldown(); } else { scrollup(); } //prevent page fom scrolling return false; }); //ie, opera, safari $('#body').bind('mousewheel', function (e) { if (e.originalevent.wheeldelta < 0) { scrolldown(); } else { scrollup(); } //prevent page fom scrolling return false; }); function scrolldown() { //scroll down console.log('down ' + scroll); if (scroll < $('#target').find('div').height() - $('#target').height() + 20) { scroll = $('#target').scrolltop() + 5; $('#target').scrolltop(scroll); } }; function scrollup() { //scroll console.log('up ' + scroll); if (scroll > 0) { scroll = $('#target').scrolltop() - 5; $('#target').scrolltop(scroll); } }; });
note added div height calculation
<div id="target"><div>.... </div></div>
you can clean code bit caching jquery variables idea there
Comments
Post a Comment