Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery animate scrollTop Not Working Properly

The following JQuery code scrolls the page to the first error in the form:

$('html,body').stop().delay(500).animate({scrollTop: $errors.filter(":first").offset().top -30},'slow');

However, if I replace the $('html,body') with the name of a container element such as a div class $('.myDivClass') with fixed positioning, it doesn't seem to work well. It just scrolls to random places up and down with each submission. If the container element is anything other than html,body, it doesn't seem to work right.

I can't figure out what I'm doing wrong.

The css of the container element looks like this (so you know what I mean):

.mcModalWrap1{
position:fixed;
top:0;
left:0;
width:100%;
padding:50px;
background-image:url(images/overlay.png);
overflow:auto;
z-index:999;
display:none;
}

I have tried using position() instead of offset() for relative positioning but it didn't make a difference.

Thank you!

Update: Looks like there is no solution for this.

like image 767
user1108996 Avatar asked Feb 10 '12 21:02

user1108996


1 Answers

I know I'm super-late to the party, but ran into the same issue, and here's how I fixed it.

When scrolling inside a fixed-positioned element, for some reason you have to add it's own scrollTop to the position to which you want to scroll, so:

var position = $errors.filter(":first").position().top + $('. myDivClass').scrollTop()
$('.myDivClass').animate({ scrollTop: position })

Worked for me.

like image 95
mtkopone Avatar answered Sep 27 '22 22:09

mtkopone