Hero Sticky Transition with 100vhDivElement

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>

Answer №1

Instead of using a constant value like 900, calculate the offset top of the div and switch to a fixed position once you reach that point. Remember to recalibrate the offset top on window resize as the content may affect its position.

Check out the code here

JavaScript:

// cache sticky div
var $sticky = $(".sticky");

// cache offset top when page loads
var stickyOffset = $sticky.offset().top;

$(window).scroll(function() {

  if( $(this).scrollTop() >= stickyOffset ) {
    $sticky.addClass('docked');
  } else {
    $sticky.removeClass('docked');
  }

});

$(window).resize( function() {
  // get offset top again when resizing
    stickyOffset = $sticky.offset().top;
});

CSS:

.sticky {
  top: 0;
  height: 55px;
  color: red;
}
.docked {
  background-color: #000;
  position: fixed;
}

The HTML remains unchanged, with updated CSS making it more streamlined. Additionally, in the JavaScript code, a class is now added instead of manipulating CSS properties each time.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The surprising twist of hasOwnProperty's behavior

I am currently working on a function that is designed to check whether an object contains keys such as 'id' or 'serif:id'. However, I have encountered some issues with its functionality. function returnIdPreferSerifId(object) { if ...

I am looking to develop a customizable table where the user can input their desired information

Looking to create an HTML page featuring a 10x10 table with alternating red and green squares. After loading the page, a pop-up window will prompt the user to input a word, which will then appear only in the red squares of the table. While I've succes ...

Having trouble with dynamic path generation for router-link in Vuejs when using a v-for loop?

//main.js import Vue from "vue"; import App from "./App.vue"; import VueRouter from "vue-router"; import HelloWorld from "./components/HelloWorld.vue"; Vue.use(VueRouter); const router = new VueRouter({ routes: [{ path: "/", component: HelloWorld }] } ...

Modifications performed on the Xhtml generated from xml and XSLT should be mirrored back into the original XML document

After transforming an XML file with xsl and loading it into a browser as html, I am making the html editable using the content editable attribute of html5. How can I transform their edits back to the original xml document, even if they add new nodes to e ...

utilizing BrowserRouter for dynamic routing in react-router-dom

I'm currently facing a challenge with creating a multi-tenant SaaS solution. Each tenant needs to be able to use a subdomain, so that I can extract the subdomain from the URL and make a call to a REST API to retrieve data specific to that tenant. For ...

Server-side rendering with the Node.js mustache template engine

I am in the process of developing a basic application for compiling mustache templates into static pages on the server side. This is what I have accomplished so far: var view = { title: "Joe", calc: function () { return 2+4; } }; v ...

Issue with triggering a modal while simultaneously closing another one

Let's consider this situation. I currently have a modal called Modal A, which has 2 buttons in the footer: Save and Close. When I click on the "Save" button, my intention is to close Modal A and open Modal B. The code that achieves this functionality ...

Differences in SVG rendering between Chrome and Firefox

I am eager to create a diagram on my website using SVG. To ensure the diagram is displayed in full screen, I am utilizing availHeight and availWidth to determine the client screen's height and width, then adjust the scaling accordingly. My current sc ...

Why is my JSON object being mistakenly interpreted as a string literal during iteration?

I'm facing a seemingly simple question but I can't seem to figure it out. Below is the jQuery code I am working with: $(function() { $.get(urlGetContainerNumbers, function(data) { console.log(data); for (var idx = 0; idx &l ...

How to Turn Off Hover Effect in Essential Grid for Mobile Devices

My website, tyloz.com, features four panels on the homepage that act as landing pages. These panels have a hover effect that also works on mobile devices. However, I am looking to disable the hover and double tap functionality specifically on phones. Is th ...

RTL in TextInput only functions properly every other time it is rendered

I am facing a strange problem with RTL where everything seems to be flipped correctly except for TextInput, which only works about half of the time. Check out this gif that demonstrates the issue as I switch between English and Hebrew: (click to view a la ...

Using Selenium and Python to showcase the source of an image within an iframe

My goal is to automatically download an image from shapeNet using Python and selenium. I have made progress, but I am stuck on the final step. from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.s ...

What is the best way to create a sticky/fixed navbar that conceals the div above it while scrolling on the page?

When I am at the top of the page, I want to display the phone number and email above the navigation bar. However, as soon as I start scrolling down, I want the phone number and email to disappear and only show the navigation bar. I have attempted using fix ...

Vue is struggling to load the component files

Lately, I've been encountering an error during webpack build that is causing some issues. ERROR There were 3 errors encountered while compiling The following relative modules could not be found: * ./components/component1.vue in ./resources/assets/ ...

The Angular Table row mysteriously vanishes once it has been edited

Utilizing ng-repeat within a table to dynamically generate content brings about the option to interact with and manage the table contents such as edit and delete. A challenge arises when editing and saving a row causes it to disappear. Attempts were made ...

Instructions on how to insert a new row into Datatables following the successful submission of a form via AJAX请求

Could someone please provide guidance on how to insert a new row into an existing datatable after a successful AJAX request? Here is the code I am currently using: $(document).ready(()=>{ $.ajax({ url: 'http://localhost:3000/api/post/getUserDat ...

Expand the clickable area of the checkbox

Is it possible to make clicking on an empty space inside a table column (td) with checkboxes in it check or uncheck the checkbox? I am limited to using only that specific td, and cannot set event handlers to the surrounding tr or other tds. The functional ...

Having trouble with the alias in commander.js not functioning as desired when using the "--help" option

Currently, I am facing a strange issue while working on my project with commander.js. The problem arises when assigning an alias for a command. I looked at some examples mentioned in the reference: Commander.JS Example I decided to create a git-like comma ...

Can someone guide me on how to organize a div structure into a table format with the help of JQuery

I am new to JQuery and I have created a table using divs instead of the traditional table structure. Each row has the same ids, which I thought would help me sort the table. Here's an example of my code: <div class="column_title">Column 1</ ...

Cookies are strangely absent from the ajax call to the web api - a puzzling issue indeed for Web Api users

Hello, here is the code I'm working with using Ajax: function GetCurrentUserId() { return $.ajax({ type: "GET", url: rootUrl + '/api/Common/CurrentDateAndUser', dataType: 'json', ...