1

I'm having troubles trying scroll automatically with javascript. My scrolling area is the body, my js code is

$("body").animate({scrollTop: $("#myDiv").position().top)

but I don't get any result: no animation and no scrolling I also tried

$("body").scrollTop($("#myDiv").position().top);

and also replacing

$("body") with $(window).

Any hint?

1
  • A quick note to add to this: unlike CSS properties, scrollTop() will not work if units are specified. scrollTop(10) is fine, scrollTop('10') is also ok, but scrollTop('10px') will fail. Commented Feb 27, 2015 at 15:33

4 Answers 4

3

scrollTop is a jQuery method which gets or sets the the offset of the current elements scroll bar, but with no animation.

You might be getting confused with the jQuery plugin scrollTo, which offers the functionality you're after.

You'd use it like;

$(window).scrollTo($('#myDiv');
Sign up to request clarification or add additional context in comments.

5 Comments

Yes, I've yet tried out the scrollTo plugin, but with no luck. In this case the code I used is equals to your suggestion.
with no luck is not very helpful. It does work, I assure you. Maybe you can provide a code snippet showing it not-working, or explaining in more detail why it isn't meeting your needs?
sorry... I continue hittin "enter" and posting Here is the code snippet: $.ajax({ type : "GET", url : projectServiceUrl + "/fetchById", data : { projectId : $(node).attr("vision-id") }, dataType : "json", success : function(result) { $(node).addClass("enlarged"); $(node).css("width", ""); enlarge(result, node); $("#visions").isotope("reLayout", function(){ var st = $(node).offset().top; $(window).scrollTo($(node)); }); } });
@stefano: works for me jsfiddle.net/Hfymd. Or even jsfiddle.net/Hfymd/1
D'OH! I am sorry, I found out: There was a problem in the CSS. I left a "overflow: hidden" int html element. I removed it and now everything works fine. many thanks for your help and your time! Stefano
1

scrollTop is a javascript attribute and you can use it like :

document.body.scrollTop = scrollValue;

or

$("body").get(0).scrollTop = scrollValue;

and there's a plugin named jQuery ScrollTo written by Ariel Flesler if you want to animate the scrolling:

http://demos.flesler.com/jquery/scrollTo/

Comments

1

Try following code,

$('html,body').animate({scrollTop: $("#myDiv").offset().top},500);

Comments

0

Note: if you have chrome://flags/#enable-experimental-web-platform-features enabled, the plugin listed above won't work. It's a known issue: https://github.com/flesler/jquery.scrollTo/issues/92

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.