Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scroll to div - jquery - specific position

I am trying this code:

  function goToByScroll(id){

        id = id.replace("link", "");

        $('html,body').animate({
            scrollTop: $("#"+id).offset().top},
            'slow');
    }

    $("#sidebar > ul > li > a").click(function(e) {

        e.preventDefault();

        goToByScroll($(this).attr("id"));           
    });

The problem is that when i click in a specific element of list, the scroll go up to the top of the window. But in my case i have a fixed div in the top, so the content is hidden by this div. Well, I want stops the scroll before the div.

any idea?

demo

like image 426
user947462 Avatar asked May 08 '26 15:05

user947462


2 Answers

You need to give the top bar an id (e.g. id="header") and then subtract that from the scrollTop attribute:

$('html,body').animate({
    scrollTop: ($("#"+id).offset().top-$('#header').outerHeight(true))+'px'},
    'slow');

Here is a working example.

like image 191
Kato Avatar answered May 11 '26 04:05

Kato


function goToByScroll(id){

        id = id.replace("link", "");

        $('html,body').animate({
            scrollTop: ($("#"+id).offset().top - $("#YOUR_FIXED_DIV").height() ) },
            'slow');
    }

    $("#sidebar > ul > li > a").click(function(e) {

        e.preventDefault();

        goToByScroll($(this).attr("id"));           
    });
like image 42
David Horák Avatar answered May 11 '26 06:05

David Horák



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!