javascript - Code screws up when viewport changes -
i have following function makes 'up-btn' appear @ bottom of page when user scrolls 250px bottom ( , not on mobile)
html ( in head tags )
<script> if ($(window).width() > 768) { $(window).scroll(function () { if ($(window).scrolltop() + $(window).height() > ($(document).height() - 250)) { $("#up-btn").fadein(500); } else { $("#up-btn").fadeout(500); } }); }; </script>
html (body)
<a id="up-btn" href="javascript:void(0);" onclick="scrolltop();"><i class="fa fa-chevron-up fa-lg"></i></a>
it works properly. however, when scale window mobile ceen size. or if window opens @ mobile size, etc. code doesn't work , button remains invisible.
wondering if there's changes code make more foolproof?
just remove if
-statement:
<script> $(window).on('scroll', function() { if ($(window).scrolltop() + $(window).height() > ($(document).height() - 250)) { $("#up-btn").fadein(500); } else { $("#up-btn").fadeout(500); } }); </script>
when said, might consider debouncing function, avoid having recalculate time, eg. recalculate when scrolling stops.