Assigning random classes from a pool of just 3 variables to over 20 different div elements

I have a total of 20 divs and three different hover effect classes. I would like to randomly assign one of these three hover effects to each div.

The JavaScript code I am using is:

<script>
$(document).ready(function () {
viewClasses = 3;
randomNumber = Math.round(Math.random() * (viewClasses - 1)) + 1;
$('.basediv').each(function(i, val) {
   $(this).addClass('view' + randomNumber); 
});
});
</script>

All my div elements have the class .basediv assigned to them

and there are CSS classes named: .view1 .view2 .view3

With the current code, all div elements end up with the same hover effect. Each div element gets either the .view1, .view2, or .view3 effect at random.

I would appreciate any guidance on this matter

Answer №1

Incorporate the random number directly into the loop by following this example:

<script>
$(document).ready(function () {
numberOfViews = 3;
$('.basediv').each(function(i, val) {
   randomNumber = Math.round(Math.random() * (numberOfViews - 1)) + 1;
   $(this).addClass('view' + randomNumber); 
});
});
</script>

Answer №2

In my opinion, it's best to relocate the randomNumber variable inside the each function:

$('.basediv').each(function(i, val) {
   randomNumber = Math.round(Math.random() * (viewclasses - 1)) + 1;
   $(this).addClass('view' + randomNumber); 
});

Answer №3

Consider implementing a solution like the following:

$('.basediv').each(function(i, val) {
    randomNumber = Math.round(Math.random() * (viewclasses - 1)) + 1;
   $(this).addClass('view' + randomNumber); 
});

$(document).ready(function () {
viewclasses = 3;
$('.basediv').each(function(i, val) {
    randomNumber = Math.round(Math.random() * (viewclasses - 1)) + 1;
   $(this).addClass('view' + randomNumber); 
});
});
.basediv{
    width:100px;
    height:100px;
}
.view1{
    background:orange;
}
.view2{
    background:green;
}
.view3{
    background:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>

<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>

<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>
<div class="basediv"></div>

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

Utilizing HTML 5 Canvas for QR Code Generation

Utilizing the repository qrcode to create QR codes. This is my Jquery code: $(".generatetext").click(function() { var x = document.getElementById("textdata").value; $('#output').qrcode(x); }); When clicking the "Generate Button," it cu ...

Trigger a function upon the initial keypress event detected on an input field

I am facing an issue with an input element that has an onkeypress event triggering a function called change(). Strangely, the function does not execute on the very first keypress. I notice that I have to input 55 instead of just 5 for the function to updat ...

Unable to showcase the chosen option utilizing select2

Utilizing angular-ui's select2 directive has been a bit of a challenge. While the functionality is there, I've encountered an issue where the selected value isn't being displayed properly due to my implementation workaround. <select ...

Storing a collection of items in an array using jQuery

Looking to organize list items from multiple lists of the same class into an array. For example: <ul class="myList"> <li>item 1</li> <li>item 2</li> </ul> <ul class="myList"> <li>i ...

changing the breadcrumb item to a dropdown item in a dynamic way

Hey there, I'm currently working on creating a breadcrumb item using Angular. Here is what I have so far: https://i.stack.imgur.com/zt5yX.png I decided to add a dropdown for the breadcrumb item, but I'm facing a challenge: I want to be able to ...

Build a stopwatch that malfunctions and goes haywire

I am currently using a stopwatch that functions well, but I have encountered an issue with the timer. After 60 seconds, I need the timer to reset to zero seconds and advance to one minute. Similarly, for every 60 seconds that pass, the minutes should chang ...

Repeating Data in MYSQL Arrays

error_reporting(E_ALL); echo "<pre>"; // IMPLEMENTATION OF TEAM DISTRIBUTION IN CONTESTS $fixtures = mysqli_query($link, "SELECT teamname FROM tourn_teams WHERE groupname='Group 1'"); $teams = array(); // LIST OF TEAMS while($row = mysqli ...

Utilizing Custom HTTP Headers in Angular 2 to Enhance Request Handling

Within my Angular 2 project, I am implementing the use of Http (@angular/http) to communicate with my API. In order for these requests to be successful, specific headers, including a JWT header, must be included in each API request. My goal is to have an ...

When delving into an object to filter it in Angular 11, results may vary as sometimes it functions correctly while other times

Currently, I am working on implementing a friend logic within my codebase. For instance, two users should be able to become friends with each other. User 1 sends a friend request to User 2 and once accepted, User 2 is notified that someone has added them a ...

Is it possible to switch out all instances of "GET" methods with "POST" throughout the codebase?

While working on a web application, we encountered caching issues with Internet Explorer (caching occurred due to the use of GET requests). The problem was resolved when users turned on "Always refresh from server" in IE's Developers Tool. Although we ...

Achieving the Perfect Alignment: Displaying Text and Progress Bar Side by Side using Bootstrap 5

How can I align the text and progress bar on the same line using Bootstrap 5? <nav class="navbar bg-light fixed-bottom"> <div class="row m-0"> <div class="col-12 countdown"> <p class=&q ...

Tips for extracting parameters from a URL using Express JS in a custom manner

Recently, I set up a server using the express package and encountered an issue while trying to extract parameters from the URL in a specific format. The URL structure is as follows: (notice there's no '?' indicating parameters). I am lookin ...

Developing a custom form validation tool using AngularJS in tandem with Django REST on the server

Currently, I am incorporating Angular on the client side to interact with a Django REST Framework backend. To expedite the launch of the project's Alpha version, we opted to utilize server-side validation directly. With Django REST, a JSON string is ...

Choosing a portion of a polyline - Google Maps Application Programming Interface

Is it possible to select only a section of a polyline in a Google Map? I have markers that are added by the user and a polyline is drawn between the markers. The polyline between two markers represents the route between the two places. I want the user to b ...

Adding and removing data table columns and data dynamically through ajax. [It functions properly when the page loads, but when I modify the list via ajax, an error occurs]

I have implemented a custom list to determine the data needs to be displayed in a data table using AJAX. Upon clicking a button in the modal, I display a list of fields in checkboxes on the same page, save it via AJAX, and reload the data table using JavaS ...

Seeing the Pending Status in Node.js

I am facing a problem with my Ajax using the POST method. I have set up a server route on node and express.js, but even though my route replies with data, the response is pending and not returning back. Client request setup $('#select-category&apos ...

What could be causing my socket to enter a never-ending loop?

Client Side Code: useEffect(() => { socketRef.current = io.connect("...", { transports : ['websocket'] }) socketRef.current.emit("online", id) socketRef.current.on("message", ({ name, message }) => ...

Real-Time Chat Update Script

Recently, I've been delving into PHP and attempting to create a live chat web application. The data for the chat is stored in a MySQL database, and I have written a function called UpdateDb() that refreshes the chat content displayed in a certain div ...

The smooth scrolling effect I had programmed suddenly came to a halt

I have a simple jQuery script that allows for smooth navigation through a website using animated scrolling. jQuery(".main_menu li a").click(function() { var href = jQuery(this).attr('href'); if(jQuery(this).html() == 'Home') ...

Having trouble with Bootstrap's validation for file input type?

I'm struggling with implementing bootstrap validation for an input field of type 'file'. Despite not selecting a file, the form is validated. It should require at least one file, be of a specific type, and within a set size limit. I can see ...