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

129
Visualizações
How to access offsetTop property of div in reactive variable?

I have the following (simplified) structure:

DIV 1 (changing height because of an accordion)
–––--
DIV 2 (getting pushed down, offsetTop changing accordingly)

I want to assign offsetTop to a reactive variable in Svelte to be able to do calculations based on the current offsetTop of DIV 2.

What I have tried:

<script>
let mapContainer;
$: map_offset = mapContainer?.offsetTop;
</script>

<div id="div1">
<!-- more going on here -->
</div>
<div id="div2" bind:this={mapContainer}>
{map_offset}
</div>

I used optional chaining to prevent the following error:

TypeError: Cannot read properties of undefined (reading 'offsetTop')

I am not getting errors anymore and map_offset is populated with a value when the page loads, but it does not change when DIV 1 changes its height although I have checked that mapContainer.offsetTop has changed. What can I do?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your code looks perfectly fine and should work in my opinion. I would have written it the same way, and I cannot understand why the reactive statement does not run.

Hopefully someone else will come up with an explanation.

In the meantime, all I can offer is a workaround using afterUpdate which is a Svelte lifecycle function that gets called everytime the component is updated:

<script>
import { afterUpdate } from 'svelte';

let mapContainer;
let map_offset; // needs to be declared if you comment out the reactive statement
// $: map_offset = mapContainer?.offsetTop;

afterUpdate(() => {
  map_offset = mapContainer.offsetTop;
});
</script>

<div id="div1">
<!-- more going on here -->
</div>
<div id="div2" bind:this={mapContainer}>
{map_offset}
</div>

REPL example

about 4 years ago · Juan Pablo Isaza Relatório
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