Trying to incrementally animate "marginTop" with jQuery, but it resets each time. Why?
Question by K.K. Smith
I’m having trouble implementing a “scroll more text” feature.
<a href="#" id="scroll-trigger">More</a>
<div id="outer-frame">
<div id="scroll-frame">
.. long text
</div>
</div>
.. in the css
#outer-frame {
height:200px;
overflow:hidden;
}
and the Jquery ..
$(document).on("click","#scroll-control",function(e){
(e)preventDefault();
$('.scroll-frame').animate({"marginTop":"-=50px"},1000);
});
That’s the basic construction. There is more to it, but even when I have stripped down to this it does not work like I would expect.
I simply want the user to be able to scroll the text up by 50px increments.
But each time the #scroll-trigger is clicked, the .scroll-frame “resets” and scrolls from 0 up to -50px.
I have tried grabbing the dynamic CSS each time
$(document).on("click","#scroll-control",function(e){
(e)preventDefault();
var newMarginTop = ($('.scroll-frame').css('marginTop')); // should get the new value?
newMarginTop -= 50;
$('.scroll-frame').animate({"marginTop": newMarginTop },1000);
});
That didn’t work either. It still resets and scrolls from zero. What am I not getting? I’m looking at the jQuery manual and this ..
$("#left").click(function(){
$(".block").animate({"left": "-=50px"}, "slow");
});
.. moves the box progressively more and more to the left. Why is my situation different?
Answer by Starx
-
Your
animate()
property is invalidanimate({"marginTop":"-=50px"}
animate({"left": "-=50px"}
Remove the
=
sign from theseIn case you are trying to set the new values 50px less, you can try something like this.
animate({"marginTOp" : $(this).css("marginTop")-50 });
-
You are using the event object on the wrong way
(e)preventDefault();
Change this to
e.preventDefault();