Reputation: 55
I have an element <div class="stock-list-head"></div>
. This element contains titles for list of products (Article Number, Article Name, Price...).
So, I want this div
to be fixed while scrolling products (Actually, products have to go behind the <div>
while scrolling).
I tried with jquery function that catches scroll event:
$( document ).scroll(function(){
var scroll = $(window).scrollTop();
if(scroll>1){
$(".stock-list-head").css("position", "fixed");
$(".stock-list-head").css("top", "10px");
$(".stock-list-head").css("marginTop", "-101px");
// And some similar styles but without success.
}
}
All the time, the div is going down for 50px and is getting fixed in there.
Upvotes: 0
Views: 166
Reputation:
This should fix the problem:
body {
height: 1500px;
}
* {
margin: 0;
}
h2 {
margin: 0 16px;
display: inline-block;
font-size: 32px;
line-height: 56px;
}
header {
overflow: auto;
}
header,
#header-fix {
display: block;
height: 56px;
box-sizing: border-box;
background: #5b27ad;
color: white;
font-weight: 700;
font-family: "Roboto", sans-serif;
margin: 0;
}
header.fixed {
top: 0;
left: 0;
position: fixed;
z-index: 9999;
width: 100%;
}
div.fixed {
height: 0;
display: none;
}
div {
width: 300px;
height: 200px;
margin: 8px;
display: inline-block;
background: seagreen;
}
<header class="fixed">
<h2>Logo here</h2>
</header>
<div id="header-fix" class="fixed"></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
Also, you can use another method (but it may be poor in some cases) - add CSS
body {
margin-top: <here header height>; /* you can check height with devtools */
}
or use padding-top
Upvotes: 2
Reputation: 106
Try This Code
$( document ).scroll(function(){
var scroll = $(window).scrollTop();
if(scroll>1){
$(".stock-list-head").css("position", "fixed");
$(".stock-list-head").css("top", "0px");
// And some similar styles but without success.
}else if(scroll == 0){
$(".stock-list-head").css("position", "relative");
$(".stock-list-head").css("top", "0px");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header class="stock-list-head">
<h4>Header</h4>
</header>
<div>test</div>
<div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div>
Upvotes: 0