How to access offsetTop property of div in reactive variable?

Viewed 142

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?

1 Answers

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

Related