Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Get the position of an inline-block element

$
0
0

I'm trying to get the final position on screen of a div element part of a Svelte 4 component, which is instanced several times over the page.

I've been trying several ways, including that one, but I always get positions that are inconsistent with what I see on the screen. The first element, for example, returns a top position of more than 300px, even though the first element is visually on the top of the page.

Why is that, and how to get the proper position?

<script>import { onMount } from "svelte"import { scale } from "svelte/transition"import { quintIn } from "svelte/easing"import { tick } from "svelte"export let titleexport let htmlContent = nulllet positionCalculated = falselet windowDivonMount(async () => {    await tick() // Wait for component to be loaded    if (windowDiv && !positionCalculated) {        // Add some random values to the position after div size is known and different from the previous ones        const body = document.body        const html = document.documentElement        const scrollTop =            window.pageYOffset || html.scrollTop || body.scrollTop || 0        const scrollLeft =            window.pageXOffset || html.scrollLeft || body.scrollLeft || 0        const box = windowDiv.getBoundingClientRect()        const posTop = box.top + scrollTop        const posLeft = box.left + scrollLeft        console.log(            `Initial position of ${title}: left: ${posLeft}, top: ${posTop}`,        )        positionCalculated = true    }})</script><div    class="window"    bind:this={windowDiv}    in:scale={{ duration: 500, easing: quintIn }}><h1 class="window-title">{title}</h1>    {#if htmlContent}<div class="content">{@html htmlContent}</div>    {/if}</div><style>    .window {        display: inline-block;        min-width: 250px;        max-width: 600px;    }</style>

Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>