Shuffle divs in a header using JavaScript and jQuery - Effortlessly arranging elements

I have successfully designed a captivating header, and now I am faced with the challenge of randomly placing star-shaped divs throughout it. These stars are implemented as spans with a 'star' class, which is stylized by CSS to create an actual star shape. However, my dilemma arises when attempting to position these 50 stars in random locations across the header. I initially tried generating a random number and assigning it to the star class's margins, but this resulted in all stars having the same margin values. My goal is to use percentage-based margin-top and margin-left properties to achieve the desired random positioning effect. Despite multiple attempts at setting these percentages directly on the div elements, I have been unable to achieve the desired randomness in placement. You can view a demo of my code on CodePen. Here is a snippet of my code:

<div class="header" id="head">
<div class="starholder" id="holdstar">

</div>
<div class="top_nav">
    <i class="fa fa-bars"></i>
</div>
<div class="text text-center">
    <p id="name">Nick <span id="lastname">D</span</p>
</div>
    <div class="mtn1">
    </div>
    <div class="mtn2">
    </div>
    <div class="mtn3">
    </div>

$(document).ready(function() {
//Name hinge
$("#name").click(function() {
    $(".text").addClass("bounce");
    setTimeout(function() {
            $(".text").removeClass("bounce");
    }, 3000);
});


// create stars and place them at random
function createStar() {

    var holder = document.getElementById("holdstar");

    for (var i = 0; i < 50; i++) {
            var percent = Math.floor((Math.random() * 100) + 1);
    var string = percent + "%"

    var percenttwo = Math.floor((Math.random() * 100) + 1);
        var stringtwo = percenttwo + "%";

        var star = document.createElement("span");
        star.className = "star";

$(".star").css({
    "margin-top": string,
    "margin-left": stringtwo
});
        document.getElementById("holdstar").appendChild(star);
    }
};


createStar();

});

I have scoured various resources for solutions, yet none seem to address the issue when dealing with multiple divs. Any assistance would be greatly appreciated.

Answer №1

Not quite sure what kind of impact you are aiming for, but let me shed some light on why your randomness isn't really random (meaning that each element has the same margin in your CodePen).

Instead of using '.star' as your selector to style the margins of the elements (which ends up selecting all stars), it would be more appropriate to pass the variable star that you just defined:

$(star).css({
  "margin-top": string,
  "margin-left": stringtwo
});

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

I'm having trouble grasping the project layout of a Vue project that was generated using vue-cli

Having recently ventured into Vue.js with no prior experience in frontend frameworks, I embarked on a project using the "vue create" command along with standard plugins. Everything seemed to be running smoothly until I decided to start from scratch by dele ...

Start by adding a header from a different document to the top of the page

I have a pre-made header located on my server that I would like to add to specific pages on my website. What is the simplest method to achieve this? I was considering using the jQuery .prepend() function, however, I am struggling to successfully loa ...

Angular: Preserve the URL even when encountering a 404 page

Creating a custom 404 page in Angular 4 is something I have recently done, and I am looking for a way to preserve the incorrect URL that was input by the user. To see an example of this behavior, you can visit sites like GitHub. They show a 404 page when a ...

Angularjs: Adding Negative and Positive Numbers

How can I extract negative numbers and positive numbers separately from JSON data obtained from the server using the $http.get method? One of the fields in the data is called Credits, which contains both negative and positive values. Can anyone help me wit ...

Exploring Karma and Jasmine for Testing Angular Controllers Module

In an attempt to test my application, I have each controller defined in its own module rather than as a controller of the main app module, and then loaded as a dependency of the main app module. While running a test to check if the loginController is defin ...

Exploring jQuery selectors with a looping mechanism to trigger click events

Trying to figure out how to loop through numerical selector values in JQuery while utilizing an onClick event handler. Is this a chicken-or-egg situation or perhaps a closure issue? Any guidance would be appreciated. $("#q01").click(function() { cle ...

Position a single sizable DIV in line with two smaller ones

I'm attempting to create a layout similar to this: Here is the code snippet I am using: !-- BIG ONE LEFT --> <div class="container"> <div class="row"> <div class="col-lg-8"> <div class="row"> ...

Why is the startsWith function not returning the expected result in my code? What could be causing this issue?

I have a code snippet that sorts a list based on user input, but it fails if the user's input contains spaces. How can I modify the code to handle inputs with spaces without removing the spaces between characters? For example, if the user input is &ap ...

What caused the failure of the ++ operator in production mode?

Encountering an issue with a reducer in my code. There is a button with an onClick function that triggers a NextBox action to alter the state of a React UseContext. The application was built using Vite, and while running npm run dev, everything functions a ...

The accuracy of Google Maps is compromised when the width is expanded

Here's a piece of code I use to adjust the size of the Google Map container: var myMap = document.getElementById('googleMap'); myMap.classList.toggle('fullscreen'); And here is the corresponding CSS: .fullscreen { width: 100% !i ...

"Ensuring function outcomes with Typescript"Note: The concept of

I've created a class that includes two methods for generating and decoding jsonwebtokens. Here is a snippet of what the class looks like. interface IVerified { id: string email?: string data?: any } export default class TokenProvider implements ...

Exploring the benefits of utilizing appcache in combination with PHP and a database

My focus is on developing web apps using jQuery Mobile that interact with a database via PHP to retrieve prices and other important information. To ensure accessibility even when offline, I have implemented appcache for my apps. <html manifest="manifes ...

Issue with ASP.NET C# querying MS Access database

I am experiencing issues with the like query not working. Can someone help me troubleshoot? Below is the code I am using: string Item_Name = txt_search.Text.Trim(); string Conn = ConfigurationManager.ConnectionStrings["AjitConnectionString"].ToString(); ...

What is the best way to create a JavaScript function that can receive and "pass along" a varying number of parameters?

Is there a way to create a Javascript function that can accept a variable number of parameters and pass them on to other anonymous functions? Let's consider an example scenario where a method needs to trigger an event: function fireStartedEvent(a,b, ...

What is causing the internal server error in my Rails AJAX request?

I have a table with links on each line <%= link_to 'Delete', [lesson.group, lesson], remote: true, method: :delete%> The goal is to delete the corresponding database entry and remove the line from the table without refreshing the page. T ...

Is the order of items guaranteed when reading a file in node.js?

Within my node.js application, I have a test data file which I utilize to populate certain inputs. This file is structured as an array of objects. To read the data, I implement the following: data = fs.readFileSync(fileName, "utf8"); An excerpt from my ...

The process of passing parameter values by function in useEffect

Hi everyone, I hope you're all doing well. I'm currently facing an issue with trying to retrieve data from my API using the post method. The problem is that I can't use useEffect in any parameter. So, my workaround is to pass the data throug ...

How can we choose a specific array object that correlates with another?

Imagine you have an array named "test" and it's defined as var test = [1, 2, 3, 4];. Is there a method to specifically select the number 2 based on the condition that it is less than 3? If my explanation wasn't clear enough, please let me know w ...

Exploring Heroes in Angular 2: Retrieving Object Information by Clicking on <li> Items

Currently, I am delving into the documentation for an angular 4 project called "Tour of Heroes" which can be found at https://angular.io/docs/ts/latest/tutorial/toh-pt2.html. <li *ngFor="let hero of heroes" (click)="onSelect(hero)">{{hero.name}}< ...

What is the best way to change the CSS of a particular element within the #shadow-root (open)?

Can you help me modify the display of the p element inside the SR element with the #one id using CSS? #one ?SHADOW-ROOT-QUERY-SELECTOR? p { display: none}; <div> <p>My Website</p> <div id="one"> <!--#shadow-root (o ...