Adjust the element's height as you scroll

I am currently experimenting with a method to dynamically increase the height of an element based on user scrolling behavior. Despite trying multiple approaches, I have encountered challenges in getting it to work effectively.

The concept is as follows:

I aim to create a div that replicates the content of another div located below it. However, this replicated div should have an adjustable height that changes as the user scrolls through the page.

This setup would result in the duplicated div smoothly following the user's scroll position, creating a visually appealing effect.

One practical application of this technique is to blur the background behind a menu, simulating frosted glass and achieving cross-browser compatible background blur effects.

This project draws inspiration from code by Chris, which can be found here.

You can view my Codepen demonstration here.

Javascript

const content = $('#content');
const blurredContentFrame = $('#blurredContentFrame');

$(document.body).append(
    '<div id="blurredContentFrame">' +
    '<div id="blurredContent"></div>' +
    '</div>');

content.clone().appendTo('#blurredContent');

$(window).scroll(function () {
    const fromTop = $(window).scrollTop();
    const heightCalc = (398 + fromTop);
    blurredContentFrame.css('height', heightCalc + 'px');
    console.log(fromTop);
    console.log('heightCalc:' + heightCalc);
    console.log('Height:' + blurredContentFrame.css('height'));
});

CSS

body {
  height: 100%;
  width: 100%;
}
#content {
  display: block;
  background-image: url('https://images.unsplash.com/photo-1477346611705-65d1883cee1e?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=4e58a56fd7bd17453e3cf914aa365870&auto=format&fit=crop&w=1350&q=80');
  background-size: cover;
  height: 100%;
  width: 100%;
}

.article__description {
  height: 1000px;
}

#blurredContentFrame {
  overflow-y: hidden;
  display: block;
  z-index: 150;
  height: 100px;
  text-align: center;
  margin: 0 auto;
  top: 0;
  position: absolute;
  width: 100%;
}
#blurredContent {
  margin: 0 auto;
  height: 100%;
  width: 100%;
  text-align: center;
  overflow-y: hidden;
  right: 5vw;
  left: 0;
  top: 0;
  position: absolute;
  filter:blur(4px);

HTML

<body>
  <div id="content">
    <p class="article__description">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in lobortis ex. Suspendisse vestibulum varius porta. Ut ligula risus, fermentum nec elit eget, feugiat consequat diam. Donec accumsan tristique convallis. Curabitur sit amet facilisis sapien.
      Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Quisque sollicitudin augue et metus volutpat pellentesque. Maecenas dui quam, iaculis at massa in, varius varius lectus. Fusce efficitur justo sed lobortis efficitur.
      Sed vel quam at mi tristique convallis non id justo. Vestibulum molestie odio sed congue tempor. Mauris at nisl a risus finibus efficitur. Mauris quis luctus erat, id auctor tellus. Nulla vel suscipit metus. Donec porta dapibus eros et finibus.
      Maecenas suscipit nisl sed dictum luctus. Proin suscipit laoreet ante a dictum. Donec ornare, erat quis dignissim maximus, neque ex laoreet massa, sed convallis turpis turpis ut elit. Suspendisse varius augue ante, sed fermentum dui facilisis non.
      Nulla neque leo, placerat ut tempor quis, ornare sed lorem. Mauris egestas sem non magna semper lobortis. <br/>
      <mark>Note that our store is closed on Christmas eve and Christmas day.</mark>
    </p>
  </div>
</body>

Output from console.log indicates the following:

https://i.stack.imgur.com/ItNGS.png

Answer №1

The issue lies in this section

const data = $('#data');
const blurredData = $('#blurredData');

$(document.body).append(
    '<div id="blurredData">' +
    '<div id="blurredContent"></div>' +
    '</div>');

content.clone().appendTo('#blurredContent');

You are attempting to locate the element before it has been added to the page. Simply modify it to the following

const data = $('#data');

$(document.body).append(
    '<div id="blurredData">' +
    '<div id="blurredContent"></div>' +
    '</div>');

const blurredData = $('#blurredData');

data.clone().appendTo('#blurredContent');

Answer №2

https://codepen.io/example/23/

Instead of utilizing the Jquery $() method, I opted for document.getElementById.

I made the decision to reposition the content and blured declaration afterwards.

$(document.body).append(
'<div id="blurredContentFrame">' +
'<div id="blurredContent"></div>' +
'</div>');

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

Utilize mouseover to rotate the camera in three.js

Is it possible to utilize Three.js to rotate a camera and view an object from all angles upon hovering with the mouse? ...

CSS directives are not compatible with Internet Explorer 8

I implemented a registration form with CSS rules that highlight error fields with a red border when users submit incorrect or empty data. However, this functionality is not working in Internet Explorer. The red border appears correctly in Firefox and Safar ...

What makes React stand out as a server side rendering technology when compared to Angular?

While delving into the world of ReactJs, I discovered a unique comparison between its rendering aspect and AngularJs. Interestingly, some refer to ReactJs as a server-side rendering technology. This revelation has truly caught me off guard! To explore fu ...

necessity for a condition in Material UI input field

I need assistance with a function that I use to incorporate Material UI text fields into my code. The issue I'm currently facing is figuring out how to dynamically add the "required" attribute based on a boolean parameter that determines whether the f ...

Issue with displaying error message on span element during validation

Is there a way you can recommend for displaying the error message within element with id #genderError instead of after it? errorPlacement: function(error, element) { if (element.attr("name") == "myoptions" ) error.appendTo('#genderError'); ...

Strange Vertical Offset Issue with Custom Fonts in CSS

I have implemented a custom font in my CSS using the following method: @font-face { font-family: 'Gabriola'; src: url('Gabriola.eot'); src: url('Gabriola.eot?#iefix') format('embedded-opentype'), ...

Using the && operator for conditional rendering in a React return statement

How should I format my return statement in a class component when using the && operator in the condition like this: if (x === null && y === null) If the condition is met, display this HTML: <div className="col-12"> <SomeComponent /> < ...

Toggle the opening and closing of React components with a map function using onclick

Implementing an onClick function within a map operation, I am encountering an issue where clicking the onClick button changes the state of all items in the map, instead of just the item clicked. This is being done using the useState hook. const [open, se ...

Issue with Jquery Conflict in WordPress

Apologies if my inquiry is not up to standard. I am currently utilizing a Google library in my project. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> The issue arises when this conflicts with the jQuery u ...

Upgrading Table Models with ASP.NET MVC 3 and Ajax

Trying to update a record list using ajax, displayed in a table where each record has a JavaScript delete link. When I load the table initially, the RemoveLink functions correctly. However, once the div "RecordListPartialView" is updated via ajax, it stops ...

Placing a div underneath a different element on a webpage

I am struggling with the placement of a div on my webpage. I have tried various methods to position it beneath two other elements without success, despite following advice from online resources. Here is the code I have been working with: ...

The VueJS component fails to load on the webpage

Here is my Vue.js component code that I am having trouble with. Despite its simplicity, it does not load correctly: Vue.component('my-component', { template: '<div>{{ msg }}</div>', data: { msg: 'hello' ...

Should pages be indexed to index.php or should the top and bottom parts of the page be created and included in all content pages?

I've been out of the webpage creation game for a while, but I've recently decided to get back into it. Like everyone else, I want to learn the best way to do this. However, I find myself facing a dilemma on how to structure my pages. My initial i ...

IItemTransform and minified files that are already in use

Summary: IItemTransform is not triggered when a minified file already exists in the same directory as the original (non-minified) file. Issue Description The problem arises due to CSS relative image references, impacting both JavaScript and CSS files when ...

The error "ReferenceError: process is not defined in vue 3" is being

<script setup> import puppeteer from 'puppeteer'; const onChange = async () => { // Initializing the puppeteer library const browser = await puppeteer.launch(); // Creating a new page const page = await browser.newPage(); / ...

Pass a variable value as a parameter to a jQuery function using code-behind

Within my code behind, I am retrieving the [IDphoto] from an SQL database. My goal now is to pass this IDphoto as a parameter to a jQuery function upon onClick. How can I achieve this? Code behind sb.AppendFormat("<a onclick='popup()' href=& ...

Navigating between pages using React and Material UI

My concept involves a <LandingPage> with a <Top> element that can be modified by user interaction. The <Top> component contains a pageState, which can be changed by clicking buttons on the First and Second pages. Is this considered good ...

Set onfocus for DOM elements dynamically

I have a question regarding assigning onfocus or similar functions to DOM elements during runtime. Here is the scenario: <input type="text" id="box" onfocus="inputFocused()"/> Now, in a runtime assignment case: <input type="text" id="box"/> ...

Can I set a nested DIV to a higher z-index than a parent DIV in IE7, so that it appears above it?

UPDATE!!! Apologies for the confusion, it turns out the issue was with the #container DIV missing "float:left;". Please check the HTML rendering in Firefox and IE7 to see the impact! I am facing difficulty getting a nested DIV to appear above another nes ...

Is there a way for me to personalize the background of the mui-material datagrid header?

I am looking to update the background design of Mui Datagrid from this image to this image However, I am encountering an issue where the background color does not fully cover the header. I have attempted using "cellClassName:" in the columns but it has n ...