Scrolling up and down by a set amount of pixels using jQuery scrollTop

Frank Kluytmans picture Frank Kluytmans · May 10, 2013 · Viewed 6.9k times · Source

I have a list of links in a div with overflow. What I want to happen is that the user can navigate in this menu of links with an up and down button. I want the div to scroll up or down by the height of 1 link element every time the user clicks the corresponding button. I tried out some code but I can't seem to figure out how to make it scroll the right amount in both directions. Can anyone help me out?

All the links have the same class.

Edit:

I have already managed to scroll up and down. Now I just need to scroll in little steps of the 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;
            }
        }
    });
});

Answer

Mathijs Flietstra picture Mathijs Flietstra · May 10, 2013

That should be easy enough using your current code, all you have to do is get rid of the interval to stop it from scrolling repeatedly. Then you won't need the mouseleave function either, you can set the scroll variable to the same value of the height of a link tag e.g. 20 for a 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();
    }
  });

});