Randomly select and incorporate 5 classes into the mix, ensuring they are dispersed throughout and not

Hello, I'm currently working on a project that involves a simple balloon game. However, I am facing some challenges with modifications. To illustrate, let me provide a basic example using <ul> and <li>.

<ul class="balloons">
  <li class="image1" id="b_1">1</li> <!-- it can be any class, but I do not want it to be added at the beginning -->
  <li class="image4" id="b_2">2</li>
  <li class="image5" id="b_3">3</li>
  <li class="image3" id="b_4">4</li>
  <li id="b_5">5</li>
  <li id="b_6">6</li> 
  <li class="image2" id="b_7">7</li>
  <li id="b_8">8</li> <!-- are there any possibilities to add after this? -->
  <li id="b_9">9</li>
  <li id="b_10">10</li>
  <li id="b_11">11</li>
  <li id="b_12">12</li>
  <li id="b_13">13</li>
  <li id="b_14">14</li>
</ul>

<script>
    $(document).ready(function(){

        var size_balloon = $(".balloons li").size();

        var images = ["", "image1", "image2", "image3", "image4", "image5"];

        for (i = 1; i <= 5; i++){
            var random_balloon = Math.floor((Math.random() * size_balloon));

            //var random_balloon = random_balloon + 1;

            var chosen_balloon = $('#b_' + random_balloon);
            //chosen_balloon.addClass('pwb');

            chosen_balloon.addClass(images[i]);
        }
    });
</script>

This code randomly adds classes, sometimes at the very beginning, which is not desired. Can anyone offer assistance with this issue?

Answer №1

Take a look at this solution that always selects 5 unique items, excluding those defined in the exclude array.

fiddle

https://jsfiddle.net/ergec/0nogjpwL/

snippet

var exclude = [0, 1, 2, 10];
var arr = [];
while (arr.length < 5) {
    var randomnumber = Math.floor(Math.random() * 11);
    if (arr.includes(randomnumber) || exclude.includes(randomnumber)) continue;
    arr[arr.length] = randomnumber;
}
$("li").filter(function(index) {
    if (arr.includes(index)) {
        $(this).css({
            "background-color": "red"
        }).addClass("image" + arr.indexOf(index));
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
    <li>0</li>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
</ul>

Answer №2

If you need to generate a random number within a specific range, you can use the following code:

var max = size_baloon; //in this case, 'size_baloon' represents your maximum value
var min = 8; //Specify the minimum value here

var randomBalloon = Math.floor(Math.random() * max) + min;

This will ensure that the variable randomBalloon always falls between the specified minimum and maximum values.

I hope this explanation is helpful!

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

Unable to hide the mobile menu button

https://i.sstatic.net/5rdYY.pngI am currently working on a fun website project . I am facing an issue with the mobile menu button not disappearing using display:none in Safari on my iPhone when in landscape mode, even though it works fine in Chrome. My g ...

Fine-tuning typography sizes with bulma for optimal efficiency

I've been grappling with the most effective method for resizing text on mobile devices. According to the documentation, adjusting text size responsively is a relatively simple process. Just add the is-size-*-mobile class to an element and set the text ...

Using CSS to set the display property to table-cell and converting it to a

I needed a SideMenu that would match the length of the content, but for some reason, using display:table-cell caused it to display:block in both Firefox and Chrome. What could be the reason behind this inconsistency? .back-branded { background: #900; ...

How about "Can I position two divs on the right side of the page

After browsing through some StackOverflow threads and other sources, I'm still struggling to figure out how to float two divs to the right while aligning them vertically (with the "sign in" div on top). Based on my findings, here are the key points: ...

The local notification feature of the plugin is designed to function exclusively within the index.html file. An error occurs when attempting to access the 'notification'

Hey there! I'm currently working on a Cordova App (Cordova 3.4.0) and I'm encountering an issue with displaying notifications. I followed the instructions provided in this link to install the local notification plugin: https://github.com/katzer/c ...

I.E Compatibility Problem with Button CSS Styling

I've created a button with some styling that looks great on Firefox and Chrome, but unfortunately doesn't work quite right on Internet Explorer (all versions). Check out the JsFiddle DEMO : http://jsfiddle.net/Mhded/1/ Below is the code I' ...

Encountering an issue with a loop in my jQuery function - any solutions?

Having encountered an issue with a select object not working in my form-building function, I resorted to using an ajax call to fetch data from a database table. While the network tab in Chrome shows the data being retrieved successfully, the console displa ...

Incorporate an external website's header and footer onto my own website

In the process of developing a new website, subdomain.example.com, it is important to note that it will operate in a separate environment from example.com. Despite this difference, both sites will feature the same layout in order to maintain a consistent u ...

Is there a way to execute a Python script by clicking the Submit button in HTML using Django?

I am still learning how to work with Django as my framework. Currently, I have an HTML file that displays using Django. I've included a Submit button on the page. Additionally, I have a Python script stored locally on my server. Is there a method to ...

Unable to get the Express.js Router functioning correctly on my server, even in a basic scenario

I am encountering an issue with using express.Router(). It was not functioning correctly in my application for serving JSON from MongoDB, so I attempted to simplify the scenario. However, I am receiving a 404 Not Found error in the request. What steps shou ...

issues with the visual studio website code (Struggling to establish a connection between the site and a database)

Currently, I am in the process of developing a website using Visual Studio and attempting to connect it to a Microsoft SQL Server 2014 database. My learning journey has led me to a tutorial video on YouTube focusing on creating a coffee-themed website alon ...

Browser and contexmenu intersecting halfway

I have successfully implemented a custom context menu in my HTML project. It functions well, but I am facing an issue where half of the menu appears off-screen to the right. Is there a way to detect this and reposition the menu above the mouse pointer? He ...

Utilizing jQuery for asynchronous image uploading

Just started learning jQuery and I'm having trouble uploading a jpg image file using the ajax method. It seems like it's not working properly. Can anyone guide me through this process? HTML <form action="" method="POST" enctype="multipart/fo ...

Encountering "Cannot GET" error following asynchronous AJAX call in ReactJS react.Component

I'm encountering a problem with my reactjs code. After addressing issues related to asynchronous operations, I now face a blank page with an error message saying "Cannot GET /thenameofthepage." Here is the code snippet following the react.Component: ...

Populating a dropdown menu with data retrieved from a query in Microsoft SQL Server

Just starting out with Node and express and I'm attempting to populate two dropdowns with different query results. Specifically, I want one dropdown for date and another for name. I managed to successfully create a dropdown for date, but when I tried ...

Show the total amount of posts

How can I modify this line of code in a WordPress theme to display only 4 or 5 posts? <div class="mvp-feat1-list-head-wrap left relative"> <ul class="mvp-feat1-list-buts left relative"> ...

Progress of uploading files to a server using Django

I am working on a form that allows users to upload files to a server using Django's development server (with a 100mb limit until the code is pushed to Apache). I want to display a progress bar for the upload process. I found some instructions on how t ...

What is the best way to make an image expand when clicked, align it in the center of the webpage, and have it return to its original position with just one more click by utilizing

Currently, this is the code I am working with. The JavaScript functionality is working well, however, there seems to be an issue where the image does not return to its original size on a second click. Additionally, I am having trouble getting the CSS to ce ...

How can text be concealed within an input field?

My degrees converter code is functioning well, but I have an issue. When I input a number for one temperature type, the conversion for the other two types is displayed correctly. However, if I then enter a number for another temperature type, the previous ...

Transforming the initial character of a label element into uppercase

When I receive an external HTML page, all the data comes in lowercase. I attempted to capitalize the first letter of each label tag using CSS, but it ended up making the entire text uppercase instead. Here is what I tried: .fontmodal { text-transform ...