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;
});
});
$('#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/
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With