I need to make slider.
I have content (which should shift horizontally) and two buttons - "right" and "left".
If you press the button and hold it, the content starts to move (in the appropriate direction). If you not hold the button, then the movement stops. This behavior is copies the behavior of usual window scrollbar.
I wrote code:
var animateTime = 1,
offsetStep = 5;
//event handling for buttons "left", "right"
$('.bttR, .bttL')
.mousedown(function() {
scrollContent.data('loop', true).loopingAnimation($(this));
})
.bind("mouseup mouseout", function(){
scrollContent.data('loop', false);
});
$.fn.loopingAnimation = function(el){
if(this.data('loop') == true){
var leftOffsetStr;
leftOffsetInt = parseInt(this.css('marginLeft').slice(0, -2));
if(el.attr('class') == 'bttR')
leftOffsetStr = (leftOffsetInt - offsetStep).toString() + 'px';
else if(el.attr('class') == 'bttL')
leftOffsetStr = (leftOffsetInt + offsetStep).toString() + 'px';
this.animate({marginLeft: leftOffsetStr}, animateTime, function(){
$(this).loopingAnimation(el);
})
}
return this;
}
But it does have a few things that I do not like:
- Always call the function animation (
loopingAnimation
) - I think that this is an extra load (not good). - When moving content he "twitches and trembling" - (it's not pretty).
How can I solve this problem more elegantly and without the drawbacks of my code?