jas7457
jas7457

Reputation: 1991

How to scroll to an anchor with an offset?

I understand how you can easily scroll to anchors by referencing them like so...

<a href = "#div1">Click here to go to div!</a>
<div id = "div1">Stuff in your div</div>

I am having problems with this because I have a music player at the top that has its position set to fixed, so it is cutting off the top of my divs when I try to the anchor.

If you want an example, check out my page here. Click a post's picture to start playing the song, then click the "View Post" thing that SHOULD take you to the correct post, but you can see that the top is cut off.

Is there an easy way to have some type of offset or something so I can remedy this. Also, can I make it so it doesn't change the URL of the site to have /#somethinghere at the end?

Upvotes: 1

Views: 5599

Answers (1)

nejib
nejib

Reputation: 76

This is possible with javascript, offset variable must change according to the desired offset

Javascript:

function getpos(myElement)
        {
            var offset = 20;
            window.scrollTo(0, 0);
            var rect = myElement.getBoundingClientRect();
            window.scrollTo(rect.left , rect.top - offset);
        }

HTML:

<div id="yourElementId" onclick="getpos(this);">image or another element</div>

The window will scroll to the clicked element with the id 'yourElementId' and a offset of '20'

Upvotes: 2

Related Questions