Zolax
Zolax

Reputation: 91

Scroll to target inside div with overflow

Hello I want to make scroll to target inside my div with option: overflow:hidden but I doesn't work good. I don't know why my scroll script behave strange. It doesn't scroll to correct target or when I click twice on one button it back to another target. What is wrong with this? Could you help me.

$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    //shows what href contains
    var target = this.hash,
    $target = $(target);
    $('.content').stop().animate({
        'scrollTop': $target.offset().top-187 //scroll to top position on href element for example #about
    }, 1000, 'swing');
});

http://jsfiddle.net/PGnZN/1/

Upvotes: 0

Views: 999

Answers (2)

Huangism
Huangism

Reputation: 16438

You are using .offset() when you should be using .position() http://api.jquery.com/position/ .offset() gets the coords relative to the document where .position() gets the coords from the offset parent. It is important to have position relative on the parent so that the value can be calculated correctly. I did not touch the 187 assuming you wanted it to show it around the middle

http://api.jquery.com/offset/

$('.content').stop().animate({
    'scrollTop': $target.position().top-187 //scroll to top position on href element for example #about
}, 1000, 'swing');

CSS

.inside{
    max-width: 680px;
    position: relative;
}

Upvotes: 2

oiek kent
oiek kent

Reputation: 21

please try this

$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    //shows what href contains
    var targethash = this.hash,
    $target = $(targethash);
    $('.content').stop().animate({
        'scrollTop': $target.offset().top//-187 //scroll to top position on href element for example #about
    }, 1000, 'swing');
});

Upvotes: 0

Related Questions