Scrolling up and down a given number of pixels with jQuery scrollTop

I have a list of links in an overflow div. I want the user to be able to navigate this menu of links using the up and down buttons. I want the div to scroll up or down the height of 1 link element every time the user clicks the corresponding button. I tried some code, but I canโ€™t figure out how to get it to scroll the desired amount in both directions. Can anyone help me out?

All links have the same class.

Edit:

I have already managed to scroll up and down. Now I just need to scroll through the small steps with a height of 1 link.

$(function() { var ele = $('#scroller'); var speed = 10, scroll = 5, scrolling; $('.scroller-btn-up').click(function() { // Scroll the element up scrolling = window.setInterval(function() { ele.scrollTop( ele.scrollTop() - scroll ); }, speed); }); $('.scroller-btn-down').click(function() { // Scroll the element down scrolling = window.setInterval(function() { ele.scrollTop( ele.scrollTop() + scroll ); }, speed); }); $('.scroller-btn-up, .scroller-btn-down').bind({ click: function(e) { // Prevent the default click action e.preventDefault(); }, mouseleave: function() { if (scrolling) { window.clearInterval(scrolling); scrolling = false; } } }); }); 
+6
source share
1 answer

This should be easy enough using your current code, all you have to do is get rid of the interval in order to stop it from scrolling again. Then you also donโ€™t need the mouseleave function, you can set the scroll variable to the same link tag height value, for example. 20 for 20px high link tag:

 $(function() { var ele = $('#scroller'); var scroll = 20; $('.scroller-btn-up').click(function() { // Scroll the element up ele.scrollTop(ele.scrollTop() - scroll); }); $('.scroller-btn-down').click(function() { // Scroll the element down ele.scrollTop(ele.scrollTop() + scroll); }); $('.scroller-btn-up, .scroller-btn-down').bind({ click: function(e) { // Prevent the default click action e.preventDefault(); } }); }); 
+3
source

Source: https://habr.com/ru/post/944695/


All Articles