Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery mousewheel

I want to scroll the content of a div with the mousewheel jquery plugin. I have this but its not working. Any thoughts?

$(function() {
$('#contentBox').bind('mousewheel', function(event, delta) {
   if (delta > 0) {
        $('#contentBox').css('top', parseInt($('#contentBox').css('top'))+40);
    } else {
        $('#contentBox').css('top', parseInt($('#contentBox').css('top'))-40);
    }
  return false;
}); 
}); 
like image 693
user520300 Avatar asked May 15 '11 21:05

user520300


3 Answers

$('#contentBox').bind('mousewheel DOMMouseScroll', function(event) {
  event.preventDefault();
  var delta = event.wheelDelta || -event.detail;
  $(this).css({'top': $(this).position().top + (delta > 0 ? '+=40' : '-=40')});
}); 

http://www.adomas.org/javascript-mouse-wheel/

like image 185
ruvan Avatar answered Nov 14 '22 19:11

ruvan


Just a guess : does adding + 'px' to the CSS value fix things? Actually, what does 'media' refer to?

UPDATE

OK, I've had a chance to test your code and it all looks good, presuming you've set the CSS up properly. Have you actually assigned a value for top on #contentBox already? Without an existing value, parseInt($('#contentBox').css('top')) will return NaN. Here's the code that I used:

$(function() {
    $('#contentBox').bind('mousewheel', function(event, delta) {

        $('#contentBox').css('top', parseInt($('#contentBox').css('top')) + (delta > 0 ? 40 : -40));

        return false;
    });
});

#contentBox { height: 4em; background-color: #eee; border: 1px solid #ccc; position: absolute; top: 100px; width: 200px; }

<div id="contentBox"></div>

Note that I've used the ternary operator to simplify/reduce the code a bit, but this is just to keep the size of this answer down a bit, and is entirely optional. I've also just used some test CSS there to see what I'm doing; I'm sure yours is different!

like image 34
Bobby Jack Avatar answered Nov 14 '22 18:11

Bobby Jack


If you are using jQuery 1.6, you can write:

$('#contentBox').css('top','+=40');

and forget about it.

Obviously, you still need CSS to properly declare #contentBox to be in absolute positioning and all the rest.

like image 37
Simone Gianni Avatar answered Nov 14 '22 19:11

Simone Gianni