Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
            }
        }
    });
});
like image 624
Frank Kluytmans Avatar asked May 10 '13 07:05

Frank Kluytmans


1 Answers

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();
    }
  });

});
like image 78
tom-19 Avatar answered Nov 08 '22 01:11

tom-19