js the function will trigger whenever the window is resized

After creating a mesmerizing effect of random stars on the screen using a JavaScript function, I encountered an issue when resizing the window. The stars were not adjusting properly to fit the viewport, leading to a messy display with horizontal scrolling and visual inconsistencies.

I am searching for a solution to prevent this problem. Perhaps there is a way to disable and then re-enable the function so that the stars always align perfectly with the changing width and height of the window. Is there a method to ensure that previous CSS properties are cleared before applying new ones dynamically?

<style>
    body, html {margin: 0;}
    #header {display: grid;background-color: #2e2e2e;width: 100vw;height: 100vh;overflow: hidden;}
    #header i {position: absolute;border-radius: 100%;background: grey; }
</style>
<body>
    <div id="header"></div>
<script>
    window.onresize = function() {
        updateStars();
    };

    function updateStars() {
        for( var i=0; i < 400; i++) {

            var header = document.getElementById("header"),
                star = document.createElement("i"),
                x = Math.floor(Math.random() * window.innerWidth * .98),
                y = Math.floor(Math.random() * window.innerHeight),
                size = Math.random() * 1.5;
                animate = Math.random() * 50;

            star.style.left = x + 'px';
            star.style.top = y + 'px';
            star.style.width = size + 1.5 + 'px';
            star.style.height = size + 1.5 + 'px';
            star.style.opacity = Math.random();
            star.style.animationDuration = 10 + animate + 's';

            header.appendChild(star);
        }
    };
    updateStars();
</script>
</body>

Answer №1

In a nutshell, each time you adjust the size of the page, the function skyCity() is called, triggering the execution of header.appendChild(cityLight); 400 times. This results in the continuous addition of new lights...

To optimize this, you can: a) Eliminate every <i> element within #header before the loop in the skyCity() function,

and b), for a more efficient approach, initialize the 400 <i> elements once upon loading the page, and then simply update their properties on subsequent resizes.

Answer №2

It appears that the issue lies in the excessive appending of i tags or stars during resizing, rather than a CSS problem.

I recommend clearing the wrapper #header before adding additional <i>s.

You can implement something like this:

window.onresize = function() {
        createCityLights();
    };

    function createCityLights() {
      var header = document.getElementById("header")
      header.innerHTML=''
        for( var i=0; i < 400; i++) {

          
              var cityLight = document.createElement("i"),
                x = Math.floor(Math.random() * window.innerWidth * .98),
                y = Math.floor(Math.random() * window.innerHeight),
                size = Math.random() * 1.5;
                animate = Math.random() * 50;

            cityLight.style.left = x + 'px';
            cityLight.style.top = y + 'px';
            cityLight.style.width = size + 1.5 + 'px';
            cityLight.style.height = size + 1.5 + 'px';
            cityLight.style.opacity = Math.random();
            cityLight.style.animationDuration = 10 + animate + 's';

            header.appendChild(cityLight);
        }
    };
    createCityLights();
#header {display: grid;background-color: #2e2e2e;width: 100vw;height: 100vh;overflow: hidden;}
#header i {position: absolute;border-radius: 100%;background: grey; }
<div id="header"></div>

Feel free to check the full page link and experiment with window resizing.

Answer №3

You might consider maintaining the "stars" as an array (cityLights in the provided code) and updating the style whenever the browser size is altered.

<style>
    body, html {margin: 0;}
    #header {display: grid;background-color: #2e2e2e;width: 100vw;height: 100vh;overflow: hidden;}
    #header i {position: absolute;border-radius: 100%;background: grey; }
</style>
<body>
    <div id="header"></div>
<script>
    window.onresize = function() {
        skyCity();
    };

    var header = document.getElementById("header");
    var cityLights = []
    for( var i=0; i < 400; i++) {
        cityLights.push(document.createElement("i"));
    }


    function skyCity() {
        for( var i=0; i < 400; i++) {
            var cityLight = cityLights[i],
                x = Math.floor(Math.random() * window.innerWidth * .98),
                y = Math.floor(Math.random() * window.innerHeight),
                size = Math.random() * 1.5;
                animate = Math.random() * 50;

            cityLight.style.left = x + 'px';
            cityLight.style.top = y + 'px';
            cityLight.style.width = size + 1.5 + 'px';
            cityLight.style.height = size + 1.5 + 'px';
            cityLight.style.opacity = Math.random();
            cityLight.style.animationDuration = 10 + animate + 's';

            header.appendChild(cityLight);
        }
    };
    skyCity();
</script>
</body>

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

Tips on exporting the 'invisible section' as a PDF without it being displayed on the user interface

Kindly take a look at the concealed div element below. It is being utilized as a hidden component to structure the PDF contents for download as a PDF. The HTML elements are declared as follows. <div id="griddata" style="display:none;"> <div id= ...

Vue.js is encountering an issue with receiving the accurate return value from a POST function

I am facing an issue where I am unable to receive the full data that is being sent from the frontend to the backend. Here is an example of the data structure that I am sending: { _id: 64a8a8e9903039edb52ccc4c, productName: 'Vial 2ml(US) Type1&apos ...

Vue looping through nested checkbox groups

Here is an object I am working with: rightGroups: [ { name: "Admin Rights", id: 1, rights: [ { caption: 'Manage Rights', name: 'reports', ...

Arrange the header and input within a div using flexbox to achieve different alignments

I need help aligning the header section vertically and ensuring responsiveness. Using margin-top isn't fully responsive, so I want to align the header at the beginning of the input field.https://i.sstatic.net/w3xSP.jpg { margin: 0px; paddin ...

Oops! The page you're looking for at /api/tasks

Whenever I try to access: http://localhost:3000/api/tasks, I keep getting a "Cannot GET /api/tasks" error message. This is my server.js: var express = require('express'); var path = require('path'); var bodyParser = require('body ...

Showing a global variable from an external JavaScript library

I have integrated some external libraries into my ionic project. One of these libraries includes the declaration of var loading = false; In my page's .ts file, I am "importing" this variable using: declare var loading; Although I can use this vari ...

Is it considered inefficient to import every single one of my web components using separate <script> tags?

Currently, I am in the process of developing a website with Express + EJS where server-side rendering is crucial. To achieve this, I am utilizing web components without shadow dom. Each page type (home, post, page) has its own EJS view. For instance, when ...

List all directories before accessing them using fs.readdirSync

Looking to fetch the contents of a directory from my system. Here is the structure https://i.sstatic.net/Qhwkg.png This code helps me read the directory: const directoryLevelInfo = fs.readdirSync('data', 'utf8') ...

Is it possible to adjust the background size using jQuery?

When attempting to set backgroundSize with jQuery using the code provided, I consistently encounter an error on the fourth line: "unexpected identifier." bigwidth = 200; bigheight = 100; $(e.target).css({backgroundImage: 'url(' + ...

Tips for closing a MUI Modal that was opened from a parent component within a child component in React

Currently, I am in the process of constructing a modal component that can be triggered from a parent component and closed from within the modal itself using React. To achieve this functionality, I have initialized the state in the parent component and the ...

Troubles encountered when attempting to remove a Meteor.js collection with template event listeners

I am a Meteor beginner and I've been encountering some challenges that I need help with. I have set up a list of items in a Meteor (mongo) collection that can be accessed by both client and server. My goal is to be able to delete an item when clicking ...

What are some ways to conceal the API connection within a button?

I have a code that allows me to perform a certain API call with a link. Here is an example: <a class="btn btn-default" href="https://testapi.internet.bs/Domain/Transfer/Initiate?ApiKey='.$user.'&Password='.$pass.'&Domain=&ap ...

Is there a way to execute PHP scripts using JQuery or AJAX without causing the page to refresh?

REFRESHED CODE I'm attempting to execute PHP scripts within my main PHP file where all content will be presented. My goal is to exhibit the outcomes from my PHP script including the SQL queries in use. I also aim to implement the feature of showcasin ...

"Step-by-step guide on creating a popup window for editing a row using ng-grid and AngularJS

I recently started diving into angular-js and I'm really impressed with how cool it is. In my search, I came across http://angular-ui.github.io/ng-grid/, which seems to be a user-friendly tool. However, I'm grappling with figuring out how to disp ...

What are the steps to incorporating an Image in a React Native application?

My Image is not showing up when I try to render it using image uri, and I'm not sure why. Here is the code snippet I'm using in a React Native project. import React from 'react'; import styled from 'styled-components/native'; ...

Generate a new web component using JavaScript

My HTML table looks like this: <table id = "rpttable" name = "rpttable"> <thead> Column Headers here... </thead> <tbody id = "rptbody" name = "rptbody"> data here <3 .... </tbody> </table> And in my ...

What is the process for inserting HTML and CSS through the editor on DNN? Can markup be incorporated without the need for modules?

At my workplace, I do not have direct Host or Superuser access to DNN, and unfortunately, it is against company policy to grant me access to those accounts. This poses a challenge when trying to get my HTML/CSS to function correctly within the DNN HTML edi ...

Center the image within a div element

I am interested in incorporating images related to logos into the center of boxes. Is there a way I can achieve this? ...

Ways to remain on the same page even after submitting a form

I've been searching for a solution to my specific issue for days, but haven't had any luck. Can anyone provide assistance? I have a form on my website that is supposed to send an email when clicked, while also converting the div from a form to a ...

Tips for effectively utilizing Enums with switch statements in typescript

In one file, I have the following code snippet: export module Utils { export enum DataSources { SharepointList = "SharepointList", JsonData = "JsonData" }; } And in another file, there is the following code: import CustomerDAO f ...