Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
Why doesn't rootMargin of IntersectionObserver seem to be respected when evaluating a sticky element?

Looking at the IntersectionObserver API, it sounds like you can use rootMargin to specify offsets for the container to coerce the API to fire when an element is either near or some number of pixels inside a target container. But with the below example, it seems to not fire. I've set the 'rootMargin' to have an 11px top margin, so the sticky element (which sticks 10px from the top) should be partially overlapping, thus causing the observer to report a change in visibility.

This logic works fine if I have top: -1px instead of top: 10px, but from all the documentation I can find, this should work as well. I've tried a few variations of margins, negative values, etc to try to make this work, without success, but randomly guessing shouldn't be the solution.

Any idea what I'm doing wrong?

HTML:

<div class="container">
 <div class="before-content">This content should scroll off the screen</div>
 <div class="sticky">Sticky content</div>
 <div class="after-content">This is some extra content after</div>
</div>

CSS:

* {
  color: #b58900;
}

.container {
  background-color: #002b36;
}

.before-content {
  height: 50px;
}

.sticky {
  height: 30px;
  background-color: #073642;
  position: sticky;
  top: 10px;
}

.after-content {
  height: 200px;
}

JS:

const sticky = document.getElementsByClassName("sticky")[0];

const observer = new IntersectionObserver(
  ([e]) => {
    console.log(e.intersectionRatio)
    const stuck = e.intersectionRatio < 1.0;
    sticky.innerHTML  = "Sticky content (" + String(stuck) + ")"
  }, {
    threshold: [1],
    // This doesn't work; changing the css ".sticky { top : -1 }" does cause the intersect logic
    // to fire and "stuck == true", but according to mdn docs it sounds like setting rootMargin
    // this way should have the same effect.
    rootMargin: '11px 0px 0px 0px',
  }
)


observer.observe(sticky)

JSFiddle Example

about 4 years ago · Santiago Gelvez
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda