March 21, 2012

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

  1. Your animate() property is invalid

    • animate({"marginTop":"-=50px"}
    • animate({"left": "-=50px"}

    Remove the = sign from these

    In case you are trying to set the new values 50px less, you can try something like this.

    animate({"marginTOp" : $(this).css("marginTop")-50 });
    
  2. You are using the event object on the wrong way

    (e)preventDefault();
    

    Change this to e.preventDefault();

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!