jquery - Javascript syntax help for a back to top link that appears only on scroll up -
i have page set top link (in entire bar) slides down @ top of page, on scroll up.
i'm beginner javascript, have cobbled together, work (it shows on scroll up, unless we're 500px top, hides on scroll down), , uses code got here not check every pixel scrolled.
what want add if still scrolling once submenu, toplink should scroll off page again - don't need top once @ top.
i've gotten work adding second javascript script, know there must better way work in first call. second call uses window.scroll function i'm pretty sure wrong way it.
first script
// hide header on on scroll down var didscroll; var lastscrolltop = 0; var delta = 5; var submenu = $('#submenu').offset().top; $(window).scroll(function(event){ didscroll = true; }); setinterval(function() { if (didscroll) { hasscrolled(); didscroll = false; } }, 250); function hasscrolled() { var st = $(this).scrolltop(); // make sure scroll more delta if(math.abs(lastscrolltop - st) <= delta) return; // if scroll down, add class .nav-up. if (st > lastscrolltop && st ){ // scroll down $('#backtotop').removeclass('nav-down').addclass('nav-up'); $(".toplink").fadeout("fast"); } else { // scroll if(st + $(window).height() < $(document).height() && st > 500) { $('#backtotop').removeclass('nav-up').addclass('nav-down'); $(".toplink").fadein("slow"); } } lastscrolltop = st; }
second script
<script> $(window).scroll (function () {var st = $(this).scrolltop(); var submenu = $('#submenu').offset().top; if (st < submenu) { $('#backtotop').removeclass('nav-down').addclass('nav-up'); $(".toplink").fadeout("fast"); } }); </script>
fiddle html , css: https://jsfiddle.net/lu0jz3nc/11/
you should able in window scroll handler, of 1 global variable.
var min_delta = 5; var min_scrolltop = 500; var menu_height = $('#backtotop').height(); $('#backtotop').addclass('nav-up'); var lastscrolltop = 0; $(window).scroll(function (event) { var scrolltop = $(window).scrolltop(); if (scrolltop > menu_height) { if (scrolltop < lastscrolltop) { // scrolling if (scrolltop > min_scrolltop) { if (scrolltop < (lastscrolltop - min_delta)) { $('#backtotop').removeclass('nav-up').addclass('nav-down'); $(".toplink").fadein("slow"); lastscrolltop = scrolltop; } } else { lastscrolltop = scrolltop; } } else { // scrolling down $('#backtotop').removeclass('nav-down').addclass('nav-up'); $(".toplink").fadeout("fast"); lastscrolltop = scrolltop; } } else { $('#backtotop').removeclass('nav-down').addclass('nav-up'); $(".toplink").fadeout("fast"); lastscrolltop = scrolltop; } });
notice lastscrolltop
variable not updated when window has been scrolled down, past min_scrolltop
, has not changed more min_delta
.
Comments
Post a Comment