1

I'm using Javascript (no jQuery) and I have a sub-menu element that pops up which at times goes beyond the bottom of the viewer, so I used scrollIntoView to have the sub-menu instantly move to be have all the line items fully within the viewport (i.e bottom of sub-menu aligns with bottom of viewport.

document.getElementById('sub1').scrollIntoView(false);

However, I then added a 2px border to that sub-menu element, and although the line items of the sub-menu appear fully within the viewer, the border does not; it remains off the bottom of the viewport. Is there a way to include the border in the scrollIntoView without adding another element to the page?

Thanks in advance.

1 Answers1

2

Well.. According to CSS box model (official W3 spec) the border is, in-fact, outside the region of the element itself (just like margin, unlike padding)

So.. I guess all you have to do is to get the value of the top-border of your element (dynamically) and adjust the calculation of the page scroll (already answered here) and a little adjustment found here

var element = document.getElementById('sub1');
element.scrollIntoView(false);
document.documentElement.scrollTop -= element.style.borderTopWidth.slice(0, -2);
ymz
  • 6,602
  • 1
  • 20
  • 39
  • many thanks! I initially tried using a ScrollBy with an arbitrary value, in addition to the scrollIntoView, but it didn't seem to work. – Yetanotherusername Dec 14 '18 at 05:09
  • Well here is a fiddle I wrote https://jsfiddle.net/3n168sp5/.. looks fine to me. Maybe it's a view-port issue? can you reproduce this on `jsfiddle` (with view-port) or any other sandbox? – ymz Dec 14 '18 at 12:57
  • 1
    Hi ymz. I think wasn't clear in my comment/appreciation. I was saying that your suggestion worked! I was just saying that before your solution, I had tried that other method which for some reason did not work. It's all good and I've marked your answer as the solution. Thanks again. – Yetanotherusername Dec 16 '18 at 20:06