Determine the dimensions of child components within Svelte templates

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>

Answer №1

Revealing the secret of obtaining a div's dimensions is entirely possible. The method used is elegantly described here.

<script>
    export let divName;
    export let top;
    export let left;
    export let htmlContent;

    export let width;
    export let height;
</script>

<div
    id={divName}
    class="div"
    style="top: {top}; left: {left};"
    bind:clientWidth={width}
    bind:clientHeight={height}
>
    <h1>{divName}</h1>
    <article>{@html htmlContent}</article>
</div>

<style>
    .div {
        min-width: 250px;
        max-width: 600px;
        position: absolute;
        background-color: red;
    }
</style>

This particular adjustment involves connecting 2 properties to the dimensions of the DIV. This allows the parent component to connect to these properties as explained here.

If you are only concerned with adjusting the top and left positions, exporting the dimensions may not be necessary. Instead, you can handle the repositioning internally within the DIV component. Consider treating the top and left properties as initial position values, allowing the component to automatically adjust its position based on the dimensions. The choice is yours.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Detecting collisions with other objects in HTML/CSS/JavaScript while animating objects

Does anyone know how to create a dynamic character using css, html, and javascript, and detect collisions with other elements? Any suggestions or guidance would be greatly appreciated. ...

Is there a way to use Jquery to determine if a parent div contains a scroll

I'm trying to find a jQuery example that checks if any parent div has a scroll bar, but I can't seem to locate a helpful one. Here is the code snippet I am working with: <div> <div class="heading"> <div class="visit ...

Customizing TinyMCE's font style menu options

Our platform utilizes TinyMCE as in-place editors to allow users to make live edits to content. However, a challenge arises when using a dark background with light text, as TinyMCE defaults to using this text color rather than black. https://i.sstatic.net ...

Creating a notification feature for an HTML application

I am in the process of creating an HTML app through intel XDK. While I understand that using HTML to build apps is not as common, it is the language I am most familiar with, along with CSS. One feature I would like to include in my app is a weekly notific ...

Border utilities in Bootstrap 4 provide easy ways to add borders

I have been searching for a solution, but I can't seem to find it. Bootstrap 4 offers utility classes for adding and removing borders, but is there a way to define the border width or style like solid or dashed? <span class="border"></span&g ...

Adjusting the text color based on the dynamically set background color

If I have a calendar where each entry has a unique background color assigned to it (one color per user), including both light and dark colors that users can choose from, how can I set the text color to match the background style? Where should I begin wit ...

What is the best way to set a stationary background that scrolls on a responsive webpage?

I'm working on a responsive website with alternating sections featuring fixed background images where the content is meant to scroll over the image. However, I'm facing an issue on iOS where the background image zooms into a small section and sca ...

Error: The function replace cannot be used on elem

Here is what I am attempting to achieve: for loop inside the append is not working Below is my code: $('body').append( $('<section>').append( $('<form>') .attr('class', "ac-custom a ...

Customize the default tab appearance in bootstrap version 5.2

Is there a way to customize the appearance of these tabs? I'm looking to change the color to match the primary color of Bootstrap. https://i.sstatic.net/6HaUO.png instead of https://i.sstatic.net/qHUZ9.png <!DOCTYPE html> <html> & ...

Java - openpdf - Splitting words using hyphens

We are currently utilizing openpdf 1.3.26 template 2.1 to create PDFs from HTML and CSS. Within our coding, there is a div element styled as follows: .text-block{ display:block; text-align:justify; word-wrap: break-word; ...

Reverse animation transition not activating in CSS

In an attempt to create a side navbar using HTML/CSS, I implemented hover animations where hovering over an icon would cause it to double in size and disperse the rest of the items in the navbar. While I successfully achieved this animation with JavaScript ...

What is the process for placing a component on the right side of the sidebar?

Here is the code snippet I am working with: <template> <div class="main"> <sidebar /> <router-view /> </div> </template> The sidebar has a width of 260px. I need to ensure that any comp ...

applying custom font to select boxes in bootstrap

Trying to style the select option text using a Poppins font with the following class: .poppinsregular14diese00000061 { font-family: Poppins; font-weight: 400; font-size: 14px; color: #00000061; } You can view the implementation in this fi ...

Basic parallax application, failing to achieve the desired impact

My goal is to create a scrolling effect where the header text moves down slightly, adding some margin on top to keep it in view. I found the perfect example of what I want to achieve with the header text at this website: After spending hours working on i ...

Looking to retrieve a specific data element within Vue.js?

Here's a thought-provoking query for you. Imagine I have some data stored in an element in the form of an array like this: data: { product: socks, variants: [ { variantId: 2234, variantColor: 'Green', varian ...

Error: Cannot access 'addEventListener' property of null in Chrome Extension due to TypeError

I've been working on developing a chrome extension that autofills input forms in web pages. However, I encountered an error that says "cannot read properties of null." This issue arises when I try to add an event listener to a button in my code. The f ...

Unseen components and columns with Bootstrap 4

I am attempting to hide a checkbox input in the middle of some column elements using Bootstrap 4. <div class="container"> <div class="row"> <a class="col-2"> 1 of 2 </a> <input type="checkbox" class="invisibl ...

Animating several elements by toggling their classes

I'm struggling to implement smooth animations on this box. I've tried using 'switchClass' but can't seem to keep everything together. Any help would be greatly appreciated. Here is the code snippet for reference: <script src=" ...

Is it possible to use Primefaces tooltip to show at the bottom of the page

When I hover over the PrimeFaces tooltip, it displays at the bottom of the page. Here is my code and image link: <!DOCTYPE html> <h:html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com ...

The Fullpage.js embedded in an iframe is experiencing difficulty scrolling on iOS mobile devices

Trying to use Fullpage.js for a website with unique sections on different domains using full-screen iframes. However, encountering issues with scrolling on IOS mobile devices. The first solution rendered the page completely unscrollable: <iframe src=" ...