I want to achieve some kind of smooth scrolling, so I made this script:
$('a').click(function(){
var sclink = $(this).attr('href');
$('.menu').animate({
scrollTop: $(sclink).offset().top
}, 500);
return false;
});
The problem? When I click on the 'a' the offset.top()
value changes in another weird value and toggle between them? Why does this happen and how do I resolve it?
/
I think the problem is with the scroll.top()
that gets the value in another way...
jsfiddle/9SDLw/2950/
$('a').click(function(){
var sclink = $(this).attr('href');
$('.menu').animate({
scrollTop: $(sclink).position().top
}, 500);
logit('Anchor: '+sclink+'; Offset top value: <b>'+$(sclink).offset().top+'</b>')
return false;
});
I want to achieve some kind of smooth scrolling, so I made this script:
$('a').click(function(){
var sclink = $(this).attr('href');
$('.menu').animate({
scrollTop: $(sclink).offset().top
}, 500);
return false;
});
The problem? When I click on the 'a' the offset.top()
value changes in another weird value and toggle between them? Why does this happen and how do I resolve it?
http://jsfiddle/StartStep/9SDLw/2947/
I think the problem is with the scroll.top()
that gets the value in another way...
jsfiddle/9SDLw/2950/
$('a').click(function(){
var sclink = $(this).attr('href');
$('.menu').animate({
scrollTop: $(sclink).position().top
}, 500);
logit('Anchor: '+sclink+'; Offset top value: <b>'+$(sclink).offset().top+'</b>')
return false;
});
Share
Improve this question
edited Aug 11, 2017 at 13:10
Daniel
2,2955 gold badges25 silver badges44 bronze badges
asked May 7, 2014 at 7:35
KeySeeKeySee
7801 gold badge13 silver badges27 bronze badges
4
- Please use scrollTop(); – user5296864 Commented May 7, 2014 at 7:36
- Look at this page: it can help you to learn how to make smooth scrolling: creativejuiz.fr/blog/doc/demo-smoothscroll.html – Superdrac Commented May 7, 2014 at 7:37
- $(this).attr('href') : string, replace with $(this) – Hacketo Commented May 7, 2014 at 7:41
- Solved here: jsfiddle/9SDLw/5474 – KeySee Commented Aug 5, 2015 at 18:13
1 Answer
Reset to default 6Use position
instead of offset
.
The reason is offset
is relative to the viewport, as such it looks like you've scrolled too far, but this is because the top of your viewport area is being obscured by your layout, so offset
is actually not what you want, instead, position
is.
You should also add a reference to stop
before calling animate
to ensure if a user clicks in quick succession the behaviour is as expected (the animation queue is essentially flushed)
With that in mind your HTML also needs some work- the clickable link hasnt got closing tags for example.
Change your scrolling code to:
$('.menu').stop(true,true).animate({
scrollTop: $(sclink).position().top
}, 500);