MasterTX MasterTX - 3 months ago 12
CSS Question

.scrollTop to an element with fixed banner on top of screen

I have figured out how to make scrollTop like this:

$("#nav-home").click(function() {
$('html, body').animate({scrollTop: $("#content-home").offset().top}, 800);
});


But my problem is that i have a fixed banner on top of screen so when it scrolls the page part of the
#content-home
element is hidden by the banner.

Also I am using this:

var hheight = $(".mainh").height();
var theight = hheight + 14;
$("#first-content").css("margin-top", mheight + "px")


to automatically add top margin depending on height of the banner + 2*7px border (+ 14). I know it's stupid but I'am happy with it working this way.

So I am asking for something like a way to add more to the offset. Or maybe add the offset of the first element affected by "the margin calculator" I've mentioned above.

If you could help me out with this and maybe even add some tips I'd be really happy.

Answer

Why not subtract the height of the banner to the scrollTop number?

var contentTop = $("#content-home").offset().top;
var hheight = $(".mainh").outerHeight(true); // the 'true' in the statement will include the top and bottom margin of the element, if they exist.
var scrollTopY = contentTop - hheight;

$("#nav-home").click(function() {
    $('html, body').animate({scrollTop: scrollTopY}, 800);
});
Comments