Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  10] [ 1]  / answers: 1 / hits: 87255  / 6 Years ago, tue, july 31, 2018, 12:00:00

I'm trying to use scrollIntoView() in my application, but because I have a top fixed bar, when I use the scrollIntoView(), the elements will be scroll to the fixed bar back.



This means that when I try to put some element visible to the user, by scrolling the element to a visible area, it will be scrolled, but to another invisible ate that is were this fixed bar is.



Follows an example of what I'm trying to do:





let element = document.getElementsByClassName('second-element')[0];
element.scrollIntoView();

.fixed-element{
height: 30px;
width: 100%;
background-color:black;
position:fixed;
}

.parent-element {
width: 100%;
height: 40000px;
background-color:blue;
}

.element {
width: 100%;
height:100px;
background-color: yellow;
margin-top:10px;
}

.second-element{
width: 100%;
background-color: red;
height:200px;
}

<div class=fixed-element></div>
<div class='parent-element'>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='second-element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
</div>





There is any way that I could use this function in a way that the scroll elements not became invisible because of the fixed bar?



I would like a vanilla JavaScript solution. Also, and only if it is possible, a solution that doesn't need to know the existent of any fixed elements.


More From » html

 Answers
5

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>




[#53838] Friday, July 27, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
clarkulisesa

Total Points: 422
Total Questions: 93
Total Answers: 112

Location: Austria
Member since Thu, Jan 7, 2021
3 Years ago
clarkulisesa questions
Mon, Feb 24, 20, 00:00, 4 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;