Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scroll to top .offset() using percentage %

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.

like image 667
Dizzi Avatar asked Jul 18 '11 17:07

Dizzi


3 Answers

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);
like image 57
Marino Šimić Avatar answered Oct 11 '22 23:10

Marino Šimić


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.

like image 42
James Allardice Avatar answered Oct 11 '22 23:10

James Allardice


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);
like image 44
jsw1995 Avatar answered Oct 12 '22 00:10

jsw1995