2

I'm using a animated scroll to id function that works really well for a whole page, moving to different elements with specific ids in a page. What I'd like to be able to do though is have the scrolling limited to a specific div that has a height of 450, width of 910 and overflow-y:scroll set.

function goToByScroll(id){
    $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}

and then putting in a link:

<a href="javascript:void(0)" onClick="goToByScroll('1')">Go to anchor 1</a>

example from this page http://djpate.com/2009/10/07/animated-scroll-to-anchorid-function-with-jquery/comment-page-2/#comment-41618

I like how simple this is, and was hoping that could be mostly maintained (obviously it will be more involved then what it is now). It'd be great if it could keep the functionality of scrolling to a element anywhere on a page, but also having a link that made a div with overflow also scroll only. Thanks in advance for any help the community might be able to give me.

karim79
  • 339,989
  • 67
  • 413
  • 406
loriensleafs
  • 2,205
  • 9
  • 37
  • 71

2 Answers2

3

Have you tried something like this

function specific_goToByScroll(parent_id, id){
    $("#"+parent_id).animate({scrollTop: $("#"+id).position().top}, 'slow');
}

Where the parent_id is you special div with overflow, and use .position() instead because position is relative to the parent element rather than relative to the page.

ShadowScripter
  • 7,314
  • 4
  • 36
  • 54
0

ShadowScripter's answer is close and was a great starting point, but you'll notice that if you scroll to the bottommost position, the query

$("#"+id).position().top

returns a negative number for elements that are located above the bottommost element. This is because position().top returns a value relative to the parent's top, and in an overflow div, that relative top position could be less than the top of the parent's top.

One solution would be to do some extra math that accounts for the viewport size.

For my purposes, it was easier to simply record all the tops when the page finishes loading, and then grab the position from the data structure:

var anchors = ['target01', 'target02', 'target03'];
var positions = {};

window.onload = function() {

    for (var i = 0; i < anchors.length; i++) {
        var id = anchors[i];
        positions[id] = $("#" + id).position().top;
    }
};

function scrollInOverflowDiv(parentID, id) {

    var pos = positions[id];
    $("#" + parentID).animate({scrollTop: pos}, 'slow');
}
Rjak
  • 2,097
  • 4
  • 19
  • 24