Transition in CSS did not work as expected when the class of the sticky element was

My goal is to create a transition effect when an element becomes sticky on the page. However, I am facing issues with the current code that I have.

const content = document.querySelector('.contents');
const initalPos = content.offsetTop;

window.addEventListener("scroll", () => {
  if(content.offsetTop > initalPos) {
    content.classList.add('stuck');
  } else {
    content.classList.remove('stuck');
  }
});
body {
  height: 300vh;
}

.contents {
  margin-top: 50px;
  border: 1px solid black;
  position: sticky;
  top: 0;
  transition: height 3s;
}

.stuck {
  height: 100px;
  background-color: green;
}
<div class="contents">
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. 
</div>

I believe there might be something missing in correctly applying the CSS transition, can you help me identify what it is?

Answer №1

To enable the transition effect, it is necessary to have an initial fixed height set. However, if you prefer not to have this fixed height initially, you can programmatically set it after calculating it using the following approach:

const content = document.querySelector('.contents');
const initalPos = content.offsetTop;
content.style.height = content.clientHeight + 'px';

window.addEventListener("scroll", () => {
  content.classList.toggle('stuck', content.offsetTop > initalPos);
});
body {
  height: 300vh;
}

.contents {
  margin-top: 50px;
  border: 1px solid black;
  position: sticky;
  top: 0;
  transition: height 3s;
}

.stuck {
  height: 100px !important;
  background-color: green;
}
<div class="contents">
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and <span style="color:red;">scrambled it to make a type specimen book.</span> 
</div>

Answer №2

Unlike other styles, Height does not animate on its own. In order to create an animation for height, you must establish a starting and ending reference point. This is why I have included min-height to achieve the desired height animation.

If you specify a fixed height, there is a possibility that the content may overflow. Therefore, it is recommended to use the actual height of the element for animating height.

const content = document.querySelector('.contents');
const initalPos = content.offsetTop;

window.addEventListener("scroll", () => {
  if(content.offsetTop > initalPos) {
    content.classList.add('stuck');
  } else {
    content.classList.remove('stuck');
  }
});
body {
  height: 300vh;
}

.contents {
  margin-top: 50px;
  border: 1px solid black;
  position: sticky;
  top: 0;
  min-height: 50px; /* adjust according to your element */
  transition: min-height ease 1s;
}

.stuck {
  min-height: 100px;
  background-color: green;
}
<div class="contents">
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. 
</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

Angular checkbox filtering for tables

I have a table populated with data that I want to filter using checkboxes. Below is the HTML code for this component: <div><mat-checkbox [(ngModel)]="pending">Pending</mat-checkbox></div> <div><mat-checkbox [(ngModel ...

Passing a JavaScript variable to a PHP variable

Initially, I attempted to convert JavaScript to PHP, only to realize that it's not possible due to server and client side executions. Now, my goal is to send a single variable. <script type="text/javascript"> function scriptvariable() { ...

Click on a div to switch between displaying an arrow pointing to the right and an arrow

Currently working on a design for an accordion-style layout and looking to implement toggling arrow icons when the div is clicked. I have managed to toggle the content of the div successfully, but now seeking assistance in achieving the same functionality ...

The stacking order of a child element within a parent element, which has a transform

Hey there, I've encountered a problem and was wondering if you could assist me with it. In the code snippet provided below, you'll see that there are elements with: transform: translate(0,0); Within these elements, there is a "dropdown" elemen ...

Troubles with Flex wrap in CSS3 on iOS 10.3.2 browsers (Chrome and Safari)

Before sending me to other similar questions, keep in mind that I have already gone through them, attempted the solutions, and they are not resolving my issue. The problem I am encountering involves the flexbox layout. I am using the flexbox layout for ce ...

When an input field is added to an HTML form, all elements positioned below it automatically inherit its attributes

I have a unique combination of HTML and CSS code that creates an impressive login form: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Prepare to be amazed...</title> <l ...

JavaScript Variables Lose Their Values

Similar Inquiry: How can I get the response from an AJAX call in a function? I have written a function that fetches numerical data from an online file. Although the file retrieval is successful (verified by the alert message), I encounter an issue whe ...

Is there a way to update the value of a variable with the help of a checkbox?

When I check the checkbox, the specOrder const gets updated as expected. However, I am struggling to figure out how to remove the value when the checkbox is unchecked. Below is the code I have been working on: const SpecialtyBurgers = () => { cons ...

Managing memory in Three.js

I am facing an issue with managing memory in my large scene that consists of Mesh and MorphAnimMesh objects. I have tried to free up memory by removing these meshes, but it seems like the memory usage remains unchanged. for ( var i = scene.children.length ...

Trouble with Angular 7: Form field not displaying touched status

I am encountering an issue while trying to input data into a form, as it is not registering the touched status. Consequently, an error always occurs when attempting to send a message back to the user. In my TypeScript file, I am utilizing FormBuilder to c ...

Arranging elements by date in JavaScript

element, I am currently utilizing the sort() method to arrange an Array based on date values. The issue arises when some elements within the data array are missing valid dates or have incorrect formats, leading to an error message stating: "Cannot read pr ...

Grouping Columns in an HTML Table using Angular 4

I'm currently faced with the task of retrieving flat data from an API and presenting it in an HTML table using Angular 4. I'm a bit unsure about how to iterate over the data, possibly using a for-each loop. I have attempted to utilize ngFor but I ...

Unable to send a function from a parent component to a child component in React using a list

Struggling to pass a simple list from a parent to multiple child components, but unable to pass down a function. I have something identical to another working block of code, yet this one is not functioning. Anyone able to spot what's going wrong? Th ...

Does the media query max-width refer to the size of the viewport or the size of the window?

Can someone clarify whether the max-width in a media query is based on the viewport size or window size? For instance, consider this media query: @media screen and (max-width: 360px){} Would this media query be activated when the viewport reaches 360px ...

Does Koa.js have a nested router similar to Express?

Are there any libraries available that offer Express-style nested routers? For example: var koa = require('koa'); var app = koa(); var Router = require('???'); var restApiRouter = Router(); restApiRouter.get('/', function*() ...

The information displayed in Postman contains a few extra characters added to the response data

I am currently working on developing a CRUD application using PostgreSQL and Node.js. However, I have encountered an issue with sending POST requests to the server. When testing the response data in Postman, I noticed that the JSON data contains some unexp ...

The device-width value in the viewport width setting is causing issues

My angular app desperately needs a mobile responsive design as it currently looks dreadful on mobile devices. I've tried adding <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=yes">, but ...

Issue with Google Tag Manager where the class name is ending with '-ok' is causing problems

Utilizing Google Tag Manager for monitoring clicks within my search engine, which showcases various book details such as cover images, titles, and authors. When a book is in stock, it displays a checkmark and "Leverbaar" (In stock) below the price tag ($1 ...

Seeking the "onChange" functionality while implementing the "addEventListener" method

I've been busy with a React project lately. Instead of adding 'onChange' to each button within the html object like this: <input type='text' onChange={myFunction} /> I'd prefer to include it in the JS code like so: doc ...

Tips for implementing an HTML modal with AngularJS binding for a pop up effect

As a beginner in AngularJS, I am facing a challenge. I have an HTML page that I want to display as a pop-up in another HTML page (both pages have content loaded from controllers). Using the router works fine for moving between pages, but now I want the s ...