Kevin Aartsen Kevin Aartsen - 6 months ago 22
Javascript Question

How to fix a jumpy animation in HTML caused by some jQuery code?

I'm 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?

HTML code:

<!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>
</div>
</body>
</html>


CSS code:



#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: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>


jQuery code:

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


You can find a fiddle showing my issue here.

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.

Comments