My code is giving me some trouble. I want the div with text to stay at the bottom of the hero section with a transparent background. When that div reaches the top, it should stick with a black background. The issue is that I have set it in the javascript very high at 900, which I know is not ideal because it will not behave correctly on small screens. How can I adjust this based on screen size? I tried setting it to be 90% from the top, but it did not work.
Additionally, my background image fades out to black as I scroll, but once again, I had to set the scroll to 900. What is the best way to achieve this effect?
When you scroll back up, the sticky div goes below the hero, making it appear larger than intended.
$(window).scroll(function(){
$(".hero-background").css("opacity", 1 - $(window).scrollTop() / 900);
});
$(document).scroll(function() {
//detect when user scrolls to the top and set position to relative, otherwise set it to fixed
$(".sticky").css({
"top": "0",
"background-color": "black",
"position": $(this).scrollTop() > 900 ? "fixed" : "relative"
});
});
.hero {
position: relative;
height: 100vh;
background-color: #000;
}
.hero-background {
height: 100vh;
background-image: url('http://2.bp.blogspot.com/-egOH8RkBAu0/UQfDNRSwC9I/AAAAAAAAeps/5Ay3wbD0Ihk/s1600/ice-snowy-rocks-mountains-hd-background-wallpapers-widescreen-high-resolutions-025.jpg');
background-position: 50% 0px;
background-size: cover;
background-repeat: no-repeat;
}
.block {
height: 1500px;
}
.sticky {
position: absolute;
left: 0px;
right: 0px;
bottom: 0px;
height: 55px;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hero" id="hero">
<div class="hero-background"></div>
<div class="sticky">
<div class="text-block">This is some text inside of a div block.</div>
</div>
</div>
<div class="block"></div>