Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!