Reputation: 168071
I have a div element (with id target
) with several anchors in it that have ids. I have a button connected to a javascript function via onclick
property that lets the div element scroll so that a certain anchor appears at the top position within the div. The function is something like this:
scrollToTag = function(id){
var target = document.getElementById('target');
var goal = document.getElementById(id);
target.scrollTop = goal.offsetTop - target.offsetTop;
};
When the height of the div (target
) is not enough, the goal anchor does not go to the top of the div because it cannot scroll any further.
What is the best way to force it to scroll? I came up with an idea of appending a blank element with height of the div the the div itself, but I am not sure it that is good. Is there a better way to do it?
Upvotes: 2
Views: 548
Reputation: 2088
There are quite a few different ways depending on your exact situation but I would recommend the :after
pseudo element:
#target:after {
content: '';
display: block;
height: 100%
}
There is no extra markup and it forces there to be the gap at the bottom that you mentioned in your question.
Upvotes: 2