How can I fix this element so that it is at the top of the page when scrolling?

I am working on a project for my UI design class and need help fixing a scroll bar at the top of the page.

Here is what I still have: http://ieatthings.com/opinio/query.html

When you scroll, the search bar should move up the navigation bar and fit well into it so that the user can find it in the middle of the page. But the problem is that the search bar continues to grow!

I used Javascript from this tutorial: Fix object at the top of browser window while scrolling . I tried all sorts of options and combinations, but unfortunately did not get this damn thing to work.

Any suggestions?

0
source share
1 answer

You will need to use Javascript to check the position of your element ("myElement") on the page compared to how far the page scrolls. If the page has been scrolled above your element, you modify your css element to snap it to the top of the page. Note: mobile browsers do not like "position: fixed"; style.

Give the element the identifier "myElement" and paste it into your tag.

<script type="text/javascript"> var yPosition; // save original y position of element here window.onload = function(){ // once entire page is loaded this function is fired // save original y position of element before it is scrolled yPosition = document.getElementById("myElement").offsetTop; } window.onscroll = function(){ // scrolling fires this function var myElement = document.getElementById("myElement"); // for cleaner code // compare original y position of element to y position of page if( yPosition <= window.pageYOffset ){ // snap element to the top by changing css values of element myElement.style.position = "fixed"; myElement.style.top = "0px"; }else{ // re-position to original flow of content myElement.style.position = "relative"; myElement.style.top = ""; // set to default } } </script> 

Hope this helps!

0
source

Source: https://habr.com/ru/post/1484265/


All Articles