Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit of increment in scrollable areas / divs in javascript?

Tags:

javascript

css

in javascript can I make sure that my large div scroll vertically only in chunks of (let's say) 16 pixels

In java, those are called 'units of increment'.

I can't find anything similar in javascript: I want to ensure that a certain area (div) when partially scrolled is always a multiple of 16 the view.

That allows me to do tricks with background images and others.

thanks

like image 826
Zo72 Avatar asked Oct 11 '11 15:10

Zo72


2 Answers

var lastScroll = 0;
$('div').scroll(function(){
    var el = $(this),
        scroll = el.scrollTop(),
        round = lastScroll < scroll ? Math.ceil : Math.floor;
    lastScroll = round(scroll/16) * 16;
    el.scrollTop(lastScroll);
});

http://jsfiddle.net/m9DQR/2/

Ensures scrolls are done in multiples of 16 pixels. You can easily extend this to be a plugin that allows for a variable amount (not a fixed, magical 16).

like image 61
davin Avatar answered Nov 11 '22 15:11

davin


Yes, this is possible, but it will require using javascript to capture the scroll event and then manipulate it. This script (sorry jQuery is what I had) and overrides the scroll event. It then replaces it with the exact same scroll distance. You could perform your own math to adjust the value of scrollTo. We have to check both mousewheel and DOMMouseScroll events because the first is not supported by FF. This doesn't seem to apply in your case, but a user may have the number of lines to scroll set to something other than the default three. So the if statement calculates the distance. I left it in there though in case other people stumble on this question and it is important to them though.

$('body').bind('mousewheel DOMMouseScroll', function(e) {
  var scrollTo = null;
  if (e.type == 'mousewheel') {
    scrollTo = (e.wheelDelta * -1);
  }
  else if (e.type == 'DOMMouseScroll') {
    scrollTo = 40 * e.detail;
  }
  //adjust value of scrollTo here if you like.
  scrollTo = 16;
  if (scrollTo) {
    e.preventDefault();
    $(this).scrollTop(scrollTo + $(this).scrollTop());
  }
});
like image 28
mrtsherman Avatar answered Nov 11 '22 16:11

mrtsherman