Styling in Svelte/TS does not change when applied through a foreach loop

I've been experimenting with creating a unique "bubble" effect on one of my websites, but I'm facing difficulty changing the styling in a foreach loop.

Despite no errors showing up in the console, I'm at a loss as to how to effectively debug this issue.
Below is the code snippet:

<script lang="ts">
    let bubbles:HTMLDivElement[]=[];
    let loaded:number=0;
    const ballAmount:number=15;
    function moveBubbles():void {
        bubbles.forEach((element)=>{
            element.style.top=Math.round((Math.random())*100)+"vh;";
            element.style.left=Math.round((Math.random())*100)+"vw;";
        });
        setTimeout(moveBubbles,15000);
    }
    moveBubbles();
</script>

<div class="bubbles">
    <div class="circles">
        {#each {length: ballAmount} as _, i}
            <div bind:this={bubbles[i]}
                class="bubble"
                style="
                    width: {Math.random()*25}vw;
                    opacity: {Math.random()*0.1};
                    top:{Math.random()*90}vh;
                    left:{Math.random()*100}vw;
                "></div>
        {/each}
    </div>
    <div class="main">
        <slot></slot>
    </div>
</div>

<style>
    .bubble {
        transition: top left 15s linear;
        aspect-ratio: 1;
        position: absolute;
        background-color: var(--primary);
        border-radius: 100%;
        opacity: 0.02;
        z-index: 0;
    }
    .bubbles {
        width: 100vw;
        height: 100vh;
    }
    .main * {
        z-index: 5;
    }
</style>

I attempted to utilize on:load, but encountered issues getting it to trigger the function, likewise with use:moveBubbles.

Answer №1

Invalid values were assigned and ignored due to a misplaced ; after the unit:

Math.round((Math.random())*100)+"vh;";

It's important to note that when modifying the style, if there are dynamic interpolated values in the template, changes made by the script may be overridden.

Directly manipulating the DOM is generally not recommended. Instead of this approach, storing an array of objects with properties { x, y } and interpolating them in the template would be more efficient. In this way, the data can easily be changed within the script.

<script lang="ts">
  const ballAmount = 15;
  let bubbles = randomLocations();
  setInterval(() => bubbles = randomLocations(), 1000);

  function randomLocations() {
    return Array.from({ length: ballAmount }, () => ({
      x: Math.round(Math.random() * 100) + "vw",
      y: Math.round(Math.random() * 100) + "vh",
    }));
  }
</script>

<div class="circles">
  {#each bubbles as { x, y }}
    <div class="bubble"
        style="
          width: {Math.random() * 25}vw;
          opacity: {Math.random() * 0.1};
          top: {y};
          left: {x};
        "></div>
  {/each}
</div>

(Remember, it is usually necessary to clean up timeouts and intervals when a component is unmounted or destroyed to prevent memory leaks. This was omitted in the code sample for brevity.)

REPL

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

Adding an additional stroke to a Material-UI Circular Progress component involves customizing the styling properties

I am attempting to create a circular progress bar with a determinate value using Material-UI, similar to the example shown in this circular progress image. However, the following code does not display the additional circle as the background: <CircularP ...

Incorporate an image icon into an Angular grid

Currently, I am in the process of building a web application using Angular. The main goal is to create a grid and color specific cells based on data input. Below is the snippet of my HTML code: <mat-grid-list cols="10"> <mat-grid-tile * ...

Deriving union type in Typescript from values within a module or object

I'm trying to find a method similar to keyof typeof myModule in typescript. However, instead of a union of key strings, I need a union of the value types. I have a module with an increasing number of exports - myModule.ts: export const Thing1; expor ...

Include type declarations for property values that resemble arrays in a generic object

Imagine you have a function that: receives an object with multiple properties and a property name; checks if the property holds an array; if it does, performs an action (such as printing the values it contains) Here's an illustration: function pro ...

What are some ways to expand the width and increase the spacing of bootstrap cards?

On my website, I have created Bootstrap cards that are displayed on two different pages. One set of cards is shown on the landing page, where I am looking to increase the spacing between them. The other set appears on the books page, and I want to make t ...

What is the reason for the regeneration of the 2D array?

I have a method called generateWeights() that retrieves random values in an array; And a method named learn() that calls the changeWeights() method to alter the values in the array. Expected: Prior to invoking the learn() method, I anticipate receiving an ...

Creating unique styles with styled components without the use of selectors

Is it possible to achieve contextual styling without using CSS selectors? For example: <Button primary> <Text>BUTTON</Text> // if the button is primary then have 20px padding else 0 <Icon/> // if the button is primary then ...

Creating diagonal ribbon designs can add a unique and dynamic touch to any

Can anyone help me figure out how to create a ribbon similar to the image below using CSS? I have managed to make the slanted filled box with text inside, but I am having trouble with the flaps. Check out this CodePen link for reference. ...

Is it possible to rearrange the positions of 2 divs using solely CSS?

I have created a unique design. On iPad, I am assigning the class 'handHeld' to the <body>, which will trigger positional changes between optionsWrapper and #container using CSS classes I've defined below on jsfiddle.net. .handHeld d ...

Adjust the color of the text in the Stepper component using React Material UI

Is there a way to modify the text color within the stepper? Specifically, I aim to have the number 3 displayed in black instead of white: Image Link ...

Challenge with constructing HTML structures

I created a table in HTML: <table cellpadding="0" cellspacing="0" border="0" style="width:1000px" id="maintable"> <thead> <tr> <th class="asc" width="30"><h3>ID</h3></th> <th width="200">&l ...

Angular functions fail to update the loop variable

Using the documentSnapshot function in Firestore to verify the existence of a document. The function is executed in a loop up to a value of 5. However, even though the function runs 5 times, the value of 'i' always reflects the last value. The ...

Using border-spacing on table body rows exclusively

In my table, I have 2 header rows and multiple body rows. To create a spacing of 10 pixels between body rows, I used the following CSS: border-collapse: separate; border-spacing: 10px; However, this also affected the spacing in the header rows, which I w ...

Troubleshooting Vue 3 Options API custom element with non-functional Bootstrap js files

Having trouble incorporating Bootstrap 5 into a Vue 3 Options Api custom element? Check out my setup below: import { defineCustomElement } from 'vue' import 'bootstrap/dist/js/bootstrap.bundle' import App from './App.ce.vue' ...

Disabling the use of console.log() in a live environment

In an effort to disable console logs for production environments in my angular application, I implemented the code below. While it successfully suppresses logs in Chrome, IE 11 continues to display them. Here is the snippet from main.ts: if (environment. ...

Learn the method to animate changing the background-color of an element using a click function

Can you create an animation for changing the background color when clicking on an element? Most examples I've found use mouseover/hover functions, but none with a click function. The following line changes the background color without any animation: ...

Trouble with the div element's change event

Hey there! I'm having trouble with this jQuery code that is supposed to fade in or fade out a div based on its contents. Here is the HTML code: <div class="mainContentWrapper"> sample text </div> And here is the CSS code: div.main ...

Evaluation of button display based on certain conditions

I currently have two different render functions that display certain elements based on specific conditions. The first render function looks like this: private render(): JSX.Element { return ( <div> {this.props.x && this.state.y ...

What is the best way to make a div span the entire height of the body?

I have a menu that I want to wrap inside a yellow div. The yellow div should take up the entire height of the green square, regardless of the content size in the green square. For example, if the orange square expands, the yellow div should also expand. h ...

Typescript Error: TS2339: The property 'faillogout' is not found within the type '{ failed(): void; onSubmit(): void; }'

I encountered an issue with my Vue.js app using TypeScript. The error message I'm getting is: Property 'faillogout' does not exist on type '{ failed(): void; onSubmit(): void; }'. 101 | failed () { This snippet shows the s ...