Kevin Aartsen Kevin Aartsen - 6 months ago 13
jQuery Question

weird html element behaviour

I have a question.
Im using a jquery code that sets my menu position to fixed after it passes through a certain div. My problem is when i scroll past the div my html makes a weird "jump" is there a way to make the elements stay where they are?

codes:

html:

<!DOCTYPE html>
<html>

<head>
<link href='https://fonts.googleapis.com/css?family=Satisfy' rel='stylesheet' type='text/css'>
<title>random</title>
<!-- <link rel="stylesheet" type="text/css" href="styles/style.css"> -->


</head>

<body>
<div id="container">
<div id="headcontainer">
</div>
<div id="menu">
<div id="logo">
<p>
Hier komt een logo
</p>
</div>
<ul>
<li>
Home
</li>
<li>
Over
</li>
<li>
Contact
</li>
<li>
Producte
</li>
</ul>
</div>

<div id="content">
<div class="text-box">


</div>
<div class="text-box">


</div>
</div>

</div>
</body>

</html>




* {
margin: 0px;
}

body {}

h1,
h2,
h3,
h4,
h5,
h6 {}

h1 {}

h2 {}

h3 {}

h4 {}

a {}

img {}

#container {
margin-left: auto;
margin-right: auto;
width: 100%;

}

#headcontainer {
width: 100%;
height: 100vh;
background-color: pink;

}
/* navigation */

#menu {
height: 100px;
width: 100%;
background-color:red;
max-height: 100px;
border: 1px solid black;
border-top: none;


}

#menu li {
display: inline-block;
text-decoration: none;
padding-left: 20px;
position: relative;
padding-right: 20px;
}

#menu ul {
float:right;
height:100%;
width: auto;
line-height: 100px;
margin-right:25px;
}

#menu ul li {

}

#menu ul li:hover {
cursor:pointer;
color: white;
}

#logo {
height: 50px;
width: auto;
background-color: red;
float: left;
margin-top: 0px;
margin-top: 30px;
margin-left: 60px;


}

/*content*/
#content {
width:100%;
height:auto;
min-height:10000px;
margin-left: auto;
margin-right: auto;

}

.text-box {
width:40%;
height:auto;
background-color:blue;
min-height:100px;
float:left;
margin-left:5%;
margin-right:5%;
margin-top:50px;
}

</style>










$(window).scroll(function () {
if ($(window).scrollTop() > $( "#headcontainer" ).height()) {
$('#menu').css('position', 'fixed').css('top', '0');
} else {
$('#menu').css('position', 'static');
}
});


Here is the jsfiddle:
https://jsfiddle.net/oaLhehhw/

Answer

That is happening, because when you have set the position to fixed, thus losing its height and causing the document to shift to the top.

Add the height of the div as top padding using position:fixed

$(window).scroll(function () {
    if ($(window).scrollTop() > $( "#headcontainer" ).height()) {
        $('#menu').css('position', 'fixed').css('top', '0');
        var divHeight = $('#menu').outerHeight();
        $('body').css('padding-top',divHeight);
    } else {
        $('#menu').css('position', 'static');
        $('body').css('padding-top','0');
    }
});

You can find a workind demo here.