I am currently in the process of transitioning a VanillaJS website to Svelte, and I need to have divs randomly positioned on the webpage. It's important to note that each div's size can vary depending on its content, so they cannot have a fixed size set in their CSS.
I have been able to calculate a random top and left position for each div, based on the window size as the maximum, and pass it as props to each div using inline styles. However, I am facing an issue in subtracting the calculated size of each div so that the top-left position does not sometimes place the div partly off the window screen.
In Vanilla JS, I used offsetWidth and offsetHeight to obtain the calculated size of the divs, as they were HTMLElement types. But in Svelte, I encountered an error stating, "Property 'offsetHeight' does not exist on type 'Element'." I am seeking suggestions on how I can resolve this issue.
Below is the code for the main App.svelte file:
<script>
import Window from "./components/Div.svelte";
const left = Math.random() * window.innerWidth; // TODO subtract div width
const top = Math.random() * window.innerHeight; // TODO subtract div height
// THIS IS NOT WORKING
// const el = document.querySelector('#my-div')
// const left = Math.round(Math.random() * (window.innerWidth - el.offsetWidth))
// const top = Math.round(Math.random() * (window.innerHeight - el.offsetHeight))
</script>
<main>
<Div
divName="my-div"
top={top}px
left={left}px
htmlContent="My HTML content with <strong>bold text</strong> and <em>italicized text</em>."
/>
</main>
Below is the code for the div subcomponent Div.svelte:
<script>
export let divName;
export let top;
export let left;
export let htmlContent;
</script>
<div id={divName} class="div" style="top: {top}; left: {left};">
<h1>{divName}</h1>
<article>{@html htmlContent}</article>
</div>
<style>
.div {
min-width: 250px;
max-width: 600px;
position: absolute;
background-color: red;
}
</style>