I´m trying to make a scrolling effect on the page, the scroll makes a smooth effect but it miss the real position of the items, and start to bug after a few position clicks.
For example if you click on the last item it goes there, but after that if you click on the third the scroll goes to top (?). so I think i´m missing something here. anybody knows how to correct the problem?
this is my markup:
<div id="sidebar" class="clearfix">
<ul>
<li>
<a href="#one" class="scroll">Muscles - Girls Crazy Go!</a>
</li>
<li>
<a href="#two" class="scroll">Tokyo Youth sports</a>
</li>
<li>
<a href="#three" class="scroll">Harajuku Interviews</a>
</li>
<li>
<a href="#four" class="scroll">Tokyo Youth</a>
</li>
</ul>
</div>
Div to scroll example:
<div class="cinematography_box clearfix" id="two">
<div class="cinematography_item">
<img src="img/cinematography.jpg" alt="cinematography" width="700" height="397">
</div>
<div class="cinematography_info">
</div>
</div>
and my script:
jQuery(document).ready(function($) {
$(".scroll").click(function(event){
event.preventDefault();
$('#main').animate({scrollTop:$(this.hash).offset().top}, 500);
});
});
I´m trying to do this without a plugin so if there is a solution with this code it would be better!
What you want to use here is .position() , not .offset() :
$(".scroll").click(function(event){
event.preventDefault();
var scroll_to = $('#' + $(this).data('scroll-to')).position().top;
$('#main').animate({ scrollTop:scroll_to }, 500);
});
You can quick-try it in the Google Chrome Console by typing :
$(".scroll").off("click");
$(".scroll").click(function(event){
event.preventDefault();
var scroll_to = $('#' + $(this).data('scroll-to')).position().top;
$('#main').animate({ scrollTop:scroll_to }, 500);
});
Then hit enter. It'll kill your listener and attach this new one.
Notice it's a little bit off because of your 12px margin-top
on #gallery.cinematography
. Either drop it or add 12 to scroll_to
JQuery's Doc is pretty self-explanatory, but feel free to ask if there's something you don't understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With