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>