0

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/

2
  • Look here api.jquery.com/offset it gets the coordinates relative to the document so the values are not what you expect them to be Commented Jun 25, 2014 at 18:19
  • Oh, it's explain a lot of.. thanks for it. Do you have which function I can use to make it correct or is there a way to use offset? Commented Jun 25, 2014 at 18:23

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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');
});

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.