I have this javascript code that scrolls a div depending on the mouse position.
Ive got the code working, the problem is its a bit jittery. I was wondering if anybody could give me advice on how to optimise it so it runs smoothly!
To view the code please visit my jsfiddle:
http://jsfiddle.net/ENhwT/3/
I realised i was going WELL too far with this, and the solution was easy.
You calculate the new scroll position based on the EXACT mouse Position... Code Follows:
$(window).load(function(){
var container = $("#PortfolioReel");
var elem = $("#PortfolioReel div");
var max_pos = container.width();
var max_scroll = elem.width() - max_pos;
var differential = max_scroll / max_pos;
$("#PortfolioReel").mousemove(function(e){
var pos = (e.pageX - this.offsetLeft) + 1;
var scr = Math.round(pos * differential);
container.scrollLeft(scr);
});
});
You set the position in fixed large steps, so it's 'jumping'. You have to iterate in smaller steps until you reach the target position.
You shouldn't use six fixed position values, but calculate new values in timesteps.
You could use something like this to make a smoother transition:
http://api.jquery.com/animate/
Something like this should be working:
elem.animate({
scrollLeft: current + 25
}, 500, function() {
// Animation complete.
});
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