Tag Archives: css

Element position is fixed starting from a certain point

If you want an element on your html page to be fixed while you are scrolling, but you don’t want it to appear right away, you want it to appear or to be positioned with another element there down the page.

Example: you have a page of html which divided into screens, first screen is the intro, then the coming screens which come as you scroll are the html content, and you want a fixed menu to stay visible as you scroll up and down, but you want it appear after the first intro screen not from the very beginning of the html.

Let’s say we have 3 screens in the html, add the floating menu to the screen where you want to start the floating menu at it:


<div class="screen1"></div>
<div class="screen2">
 <div class="persist-menu">Menu</div>
</div>
<div class="screen3"></div>

Give them some css

.screen1{
background-color: red;
width: 100%;
height: 1080px;
}
.screen2{
background-color: blue;
width: 100%;
height: 1080px;
}
.screen3{
background-color: green;
width: 100%;
height: 1080px;
}
.persist-menu
{
position: absolute;
font-size: 40px;
}

Here are the jQuery:

function UpdateMenuPosition() { //create function to update menu position
var startingScreen = $(".screen2"), //catch the screen of the starting position of the menu and get it's position
offset = startingScreen.offset(),
visibleArea = $(window).scrollTop(), //get the top position of the visible area of the html with respect to the top of html
floatingHeader = $(".persist-menu", startingScreen )

if (visibleArea > offset.top) { //as long as the top position of the visible area is greater than the top position of the screen component
floatingHeader.css({top:(visibleArea )}); //move the menu to the top of the visible area
}
}

$(function() {
$(window).scroll(UpdateMenuPosition); //bind the window scrolling to the above function
});