Skip to content
Advertisement

Add padding-top to scroll when using href=”#id”

I have an anchor tag as follows:

<a href="#map_4D85448A3D4C4180A02BD6FC387ABC45" onclick="jumptosection('map_4D85448A3D4C4180A02BD6FC387ABC45');">A Guide</a>

It navigates to a section that has the id ‘map_4D85448A3D4C4180A02BD6FC387ABC45’. The jumptosection function is as follows:

function jumptosection(id) {
    var target = document.getElementById(id);
    if(document.all){
        document.documentElement.scrollTop = target.offsetTop;
    }else{
        var top = 0;
        do {
            top += target.offsetTop  || 0;
            target = target.offsetParent;
        } while(target);

        document.body.scrollTop = top ;
    }
    //$('#article').css.paddingTop = '55px';
    return false;

But even if I write nothing in this function, the behaviour is still the same. The problem is that I have a header strip of 92px that hides some part of the section when I click on the given anchor. How do I make it scroll to the given section while adding some pixels to escape the header?

Advertisement

Answer

It is possible. I would do it without javascript, so it works for all. Even no changes on you JS are needed.

You just need to create an empty element above the element you want to scroll to. The CSS does the magic. It creates a hidden box in the height of you offset:

HTML:

<span class="anchor" id="map_4D85448A3D4C4180A02BD6FC387ABC45"></span>
<h1>Element to scroll to</h1>

CSS:

.anchor {
    display: block;
    height: 92px;
    margin-top: -92px;
    visibility: hidden;
}

See a working demo here: https://jsfiddle.net/eczxm1rs/1/

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement