Click here to Skip to main content
15,867,756 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
Can the sticking between the pink container and the green container be undone when the pink container reaches the bottom of the green container. Can anyone help me with this.

What is the problem with my code.

Also the codepen link : Click Here

Here's the code

What I have tried:

HTML
<style>
.container1 {
  width: 500px;
  height: 400px;
  background-color: lightblue;
  text-align: center;
  margin: 0px auto;
  position: sticky;
  top: 0;
  z-index: -1;
}

.container2 {
  width: 300px;
  height: 200px;
  background-color: lightgreen;
  text-align: center;
  margin: 0px auto;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -2;
}

.container3 {
  width: 500px;
  height: 400px;
  background-color: pink;
  text-align: center;
  margin: 20px auto;
}
</style>
<div class="container1">
  <div class="container2">
  </div>
</div>
<div class="container3">
</div

<script>
  const pink = document.querySelector(".container3");
const green = document.querySelector(".container2");

function checkCollision() {
  const greenRect = green.getBoundingClientRect();
  const pinkRect = pink.getBoundingClientRect();

  if (pinkRect.bottom >= greenRect.bottom) {
    pink.style.position = "relative";
  } else {
    pink.style.position = "sticky";
  }
}

window.addEventListener("scroll", checkCollision);
  </script>
Posted
Comments
Andre Oosthuizen 8-Feb-23 9:50am    
Sticking does not give us a lot of information. Looking at the codepen, do you want the green container to go back to its original position at the top, please be specific with your question as it does not make sense right now.
KiranSharma1 8-Feb-23 9:54am    
okay! I want to achieve this thing

Video link: https://drive.google.com/file/d/1345SQW0SMLbRzVEqltphbiBw8gt64dI7/view?usp=share_link
Andre Oosthuizen 8-Feb-23 10:08am    
I am sorry but I am not opening outside links particularly from unknown sites. You need to give us more information by editing your original question.
Member 15627495 8-Feb-23 10:46am    
z-index is always positive ( n >= 0 ), change the values for z-index.

you can use an absolute position for the moving area, equals at the border-top of the layer under.

you need :
- the first top position
and
- the last bottom position too
and to set the moving area between those two set of coordinates with 2 layers ( 2 z-index ),
one for the moving area, the other for the fixed areas

you have already understand how to define all position.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900