Reputation: 287
I have a header like so:
.header-wrapper {
padding: 32px 24px 0 24px;
display: flex;
position: sticky;
top: 0;
z-index: 3;
background-color: $color-white;
}
<header class="header-wrapper">
<h2 data-qa="customersTitle" class="header-label">Customers</h2>
</header>
The header-wrapper
class is written like above and cannot be changed. It must have a display:flex;
attribute, otherwise some elements break.
What I need is: after scrolling a little bit, a shadow to appear under the header. How can I do that? (If I don't use display:flex
it works. But i need to use it)
Thanks a lot in advance!
Upvotes: 0
Views: 2540
Reputation: 1701
You can achieve this with a jQuery scroll function. I have created this as a small little demo, the styling might not be the same as yours, just make sure the classes are correct within the JavaScript!
The shadow will be added once you've scrolled 200px down. If you want to make the scroll distance bigger or smaller you can change the value at scroll_distance = 100
Note: I made the header grey just for testing purposes only right now so it's easier to see it.
$(document).ready(function() {
$(window).scroll(function() {
var scroll = $(window).scrollTop();
var scroll_distance = 100;
if (scroll >= scroll_distance) {
$(".header-wrapper").addClass("one-edge-shadow");
}
if (scroll <= scroll_distance) {
$(".header-wrapper").removeClass("one-edge-shadow");
}
});
});
.header-wrapper {
padding: 32px 24px 0 24px;
display: flex;
position: sticky;
top: 0;
z-index: 3;
background-color: #eee;
transition: box-shadow 0.3s;
}
.one-edge-shadow {
-webkit-box-shadow: 0 14px 12px -6px grey;
-moz-box-shadow: 0 14px 12px -6px grey;
box-shadow: 0 14px 12px -6px grey;
}
.wrapper {
height: 2000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header class="header-wrapper">
<h2 data-qa="customersTitle" class="header-label">Customers</h2>
</header>
<div class="wrapper">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Upvotes: 1
Reputation: 1315
Same what @Fuzion
did but with vanilla Js.
adding eventListener
on the window. which gives us scrollY
value every time the user scrolls.
checking if scrollY
is greater
then 10
add
my class
of shadow
if not remove
my class of shadow
window.addEventListener("scroll", (event) => {
let scroll = this.scrollY;
if (scroll > 10) {
document.querySelector(".header-wrapper").classList.add("shadow");
} else {
document.querySelector(".header-wrapper").classList.remove("shadow");
}
});
.header-wrapper {
padding: 32px 24px 0 24px;
display: flex;
position: sticky;
top: 0;
z-index: 3;
background-color: #eee;
}
.shadow {
-webkit-box-shadow: 0 14px 12px -6px grey;
-moz-box-shadow: 0 14px 12px -6px grey;
box-shadow: 0 14px 12px -6px grey;
}
.wrapper {
height: 200vh;
}
<header class="header-wrapper">
<h2 data-qa="customersTitle" class="header-label">Customers</h2>
</header>
<div class="wrapper">
</div>
Upvotes: 1