Fixed element in proper height

Hello! I’ve just started my adventure with JS and I need your help :raised_hands:

I’m trying to do a fixed element on the page. I’ve already done the first part, which is my elements are fixed from the top when the users scroll the website. My problem is that I don’t know how to stop the element when the height of the parent’s div is over. Currently, my fixed element is still stuck after the section where is supposed to be.

How to tell the element that is supposed to be fixed just according to the height of the parent?

Btw. I don’t want to use position: sticky; cuz Internet Explorer doesn’t accept this value and this search is used by clients from time to time.

My code:

const legend = document.querySelector('.legend');
const offset = legend.getBoundingClientRect();

window.addEventListener('scroll', function() {
  if (window.pageYOffset > offset.top){
    legend.style.position = 'fixed';
    legend.style.top = 0;
  } else {
    legend.style.position = 'relative';
    legend.style.top = '';
  }
});

I think it’s the effect of “Rubber duck debugging” :smile: :smile: :smile:

I figured out my solution. For interested:

const legend = document.querySelector('.legend');
const offset = legend.getBoundingClientRect();
const graphic = document.getElementById("graphic");
var element = graphic.offsetHeight - 100;

window.addEventListener('scroll', function() {
  if ((window.pageYOffset > offset.top) &&  (window.pageYOffset < element)){
    legend.style.position = 'fixed';
    legend.style.top = 0;
  } else {
    legend.style.position = 'relative';
    legend.style.top = '';
  }
});