I just wrote this for scrolling pages which is working fine and does what it should..
$('#nav a').click(function(){
var sid = $(this).attr('id');
$('html,body').animate({
scrollTop: $('#'+ sid +'-content').offset().top - 200}, 1000);
return false;
});
..but I want the offset to be calculated by % rather then px
ie rather then
top - 200
it could be
top - 30%
any ideas how to accomplish this?
As always any help is appreciated and thanks in advance.
Quick Edit:
The current 3 answers (thank you) seem to multiply each time which is not what I want, I wish to have a constant gap of 30% window height each time so each time the #id-content is scrolled to the top lines up with a fixed positioned sidebar I have.
My current code leaves a 200px gap but that causes an issue with different monitor/browser sizes where as a % would sort it out.
The following will position the box always 60% from the top:
var offset = parseInt($('#example').offset().top);
var bheight = $(window).height();
var percent = 0.6;
var hpercent = bheight * percent;
$('html,body').animate({scrollTop: offset - hpercent}, 1000);
You could calculate 30% of the offset and use that:
$('#nav a').click(function(){
var sid = $(this).attr('id');
var offset = $('#'+ sid +'-content').offset().top;
$('html,body').animate({scrollTop: offset - (offset * 0.3)}, 1000);
return false;
});
Here's an example fiddle showing this in action.
I know this is years old and the OP has most likely found a solution by now, but here's my simple solution for anyone who comes across this anyway..
var navBarHeight = $('#navBar').height();
$('html, body').animate({
scrollTop: $("#scrollDestination").offset().top-navbarheight
}, 1000);
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