scrollIntoView() is not working: does not taking in account fixed element
Your question is answered in this link.
var node = 'select your element';
var yourHeight = 'height of your fixed header';
// scroll to your element
node.scrollIntoView(true);
// now account for fixed header
var scrolledY = window.scrollY;
if(scrolledY){
window.scroll(0, scrolledY - yourHeight);
}
Also you can use this way:
let item = // what we want to scroll to
let wrapper = // the wrapper we will scroll inside
let count = item.offsetTop - wrapper.scrollTop - xx // xx = any extra distance from top ex. 60
wrapper.scrollBy({top: count, left: 0, behavior: 'smooth'})
Source: https://github.com/iamdustan/smoothscroll/issues/47
You can make the window scrollTo
x position 0
and y position the element's offsetTop
subtracted by the fixed element's offsetHeight
.
JSFiddle with your code: http://jsfiddle.net/3sa2L14k/
.header{
position: fixed;
background-color: green;
width: 100%;
top: 0;
left: 0;
right: 0;
}
html, body{
height: 1000px;
}
#toBeScrolledTo{
position: relative;
top: 500px;
}
<div class="header">
Header
</div>
<div id="toBeScrolledTo">
Text Text Text
</div>
<script>
window.scrollTo(0, document.getElementById('toBeScrolledTo').offsetTop - document.getElementsByClassName('header')[0].offsetHeight);
</script>