Generate a unique class for each img element randomly

Is there a way to assign each image a unique random class instead of giving all the images the same random class?

Any help would be appreciated.

$(document.body).ready(function () {
    bgImageTotal = 5;
    randomNumber = Math.round(Math.random() * (bgImageTotal - 1)) + 1;
    $('img').addClass('img' + randomNumber);
});
.img1{max-height:10px}
.img2{max-height:40px}
.img3{max-height:70px}
.img4{max-height:100px}
.img5{max-height:130px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">

Answer №1

The process of looping, generating random numbers, and assigning them:

$(document.body).ready(function () {
    var totalImages = 5;
    $('img').each(function() {
        var randomNumber = Math.round(Math.random() * (totalImages - 1)) + 1;
        $(this).addClass('img' + randomNumber);
    });
});

An important point to note is that $('img') will select all the images - hence, you need to loop through them and assign classes individually.

Answer №2

To ensure each img element has a unique random class, you can generate an array from a set:

$(document.body).ready(function () {
    var $imgs = $('img');
    var len = $imgs.length;
    
    var set = new Set;
    while (set.size != len) {
        set.add((Math.random() * len | 0) + 1);
    }
    var arr = [...set];
    $imgs.each(function(pos) { $(this).addClass('img' + arr[pos]) });
});
.img1{height:10px}
.img2{height:40px}
.img3{height:70px}
.img4{height:100px}
.img5{height:130px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">

Answer №3

The issue arises from the fact that a single random number is generated and applied to all images. To fix this, create a function within the addClass() method that will iterate over each matched element and generate a unique random number for each.

$(document.body).ready(function() {
  bgImageTotal = 5;
  $('img').addClass(function() {
    return 'img' + (Math.round(Math.random() * (bgImageTotal - 1)) + 1);
  });
});
.img1 { max-height: 10px; }
.img2 { max-height: 40px; }
.img3 { max-height: 70px; }
.img4 { max-height: 100px; }
.img5 { max-height: 130px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">

Answer №4

Great question! Don't forget to incorporate a loop into your code - that's the missing piece you need. You can use a simple JavaScript for loop or utilize jQuery each if you're already working with jQuery. Give this a try and everything should function smoothly:

Your CSS:

.img1{max-height:10px}
.img2{max-height:40px}
.img3{max-height:70px}
.img4{max-height:100px}
.img5{max-height:130px}

Your HTML:

<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">

And your JavaScript (jQuery):

"use strict";
  $(document).ready(function(){
    // In jQuery, you can select elements by ID, Class, Tag, etc. This is selecting all <img> tags on your page.
    $('img').each(function(i, e) {
       var imgNo = Math.floor(Math.random() * i + 1);
         $(this).addClass('img' + imgNo);
    });
  });

Everything should be up and running now, hope this solution helps!

Answer №5

The dollar sign function encapsulates the specified element tag within a jQuery object that includes all img elements, along with a special jQuery method that executes a function on each element in the jQuery collection by passing in the element's index and DOM element. When using .addClass on the DOM element, it needs to be enclosed within a jQuery collection. For assigning properties to individual elements, utilize the jQuery .each method.

 $('img').each(function(index, element){
   $(element).addClass('img' + randomNumber);
 })

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

Props and theme merge to create uniquely designed styled components with a thematic twist

Out of sheer curiosity, I've been incorporating styled-components into my React application. Within this framework, I make use of the recommended theme to ensure consistency in colors and sizes throughout. Currently, my approach looks something like ...

Error encountered in the JavaScript code for the voting up and down system

I have been attempting to implement a script for voting up and down using ajax and jquery from a tutorial. The issue (I believe) is that the tutorial uses jquery-2.1.1, but I am using jquery-1.10.1. This is the HTML section: <div id="links-'.$row[ ...

The jQuery autocomplete feature is malfunctioning, as it is unable to display any search

Creating a country list within an ajax call involves working with an array of objects: $.ajax({ url: '//maps.googleapis.com/maps/api/geocode/json?address=' + zipCode + '&region=AT', type: 'GET', dataType: &apo ...

Modify the color of the H1 tag exclusively within specific classes

Struggling with a formatting issue here. I'm looking to customize the colors of h1, h2, h3... when they are inside specific classes. It's mostly working as intended, however, the problem arises when the headings outside of those classes don' ...

Deactivate the button upon submission using xVal in MVC

I am currently working on an MVC app that utilizes xVal. My main goal is to integrate a loading graphic into the jquery validation process, specifically to display it once the form has been successfully validated by jquery. However, I am struggling to find ...

convert a string to JSON format using Node.js Express

Currently, I am viewing some string data in a browser that has been processed using python-node js express. The data looks something like this: In order to manipulate the data more effectively, I would like to convert it into JSON format that follows this ...

A technique, such as regular expressions, can be used to detect the quantity of newline characters in the text entered by the user in a text area

I'm trying to figure out how to count the number of newline characters (or whatever is inserted when the user presses the return key) in a textarea's value. I believe I should be using a regular expression for this task, but I'm not very ski ...

Creating a multi-filter gallery similar to the one found in WooCommerce or eCommerce platforms involves integrating various filters to allow

Looking for a dynamic multifilter gallery similar to WooCommerce/ecommerce product filters? We have three types of filter dropdowns: COLOR, SIZE, and SHAPE. For example, if you select color: red and green, size: small, and shape: round The filtering wil ...

s3 key not found, The specified key does not exist. previewing file from a web link

After utilizing paperclip and s3, I successfully uploaded a word document and now I am seeking the ability to preview it directly from the database using an iframe. https://i.stack.imgur.com/ceCPu.png <iframe src="<%= agreement.document.url(:smal ...

Warning: Unhandled promise rejection in MSSQL with NodeJS detected

Currently, I am in the process of experimenting with NodeJS to set up an API. However, whenever SQL encounters an error related to NULL columns, my http call gets stuck, and the error is displayed in the node console. The specific error I encounter is: ...

Managing concurrent users updating the same form on a web application

Imagine a scenario where user A opens a form with pre-filled data. While user A makes changes to the form data, user B also opens the same form with the data intended for user A. Just as user B begins modifying the data, user A clicks on the submit butto ...

Ways to implement div on hover in my table's td cells

Here is the HTML table code I have: <table border='1px'> <tr> <td id='td'>first</td> <td>last</td> <tr> <td id='td'>newFirst</td> <td>newSecond</td> </t ...

Reorganize divisions using Bootstrap

I am exploring different ways to manage responsiveness through the reordering of divs. While I am aiming for a solution that is highly flexible, any suggestion would be appreciated. Desktop View: https://i.stack.imgur.com/boSOa.png Mobile View: https:// ...

There seems to be an issue with the HighCharts chart export feature as it is not showing the Navigator graph

We are currently using HighCharts version 4.2.2 http://api.highcharts.com/highcharts/exporting While going through their exporting documentation, I made a decision to not utilize their default menu dropdown. Instead, I only needed access to the .exportCh ...

Utilizing Jquery Ajax to locate all `<p>` elements within the responseText

Isolating a specific section of the responseText in jQuery and Ajax is my goal. $.ajax ({ url : "/controller/action", complete : function (xhr, result) { if (result != "success") return; var response = xhr.responseText; var title = $(res ...

What is the best way to compare two arrays of objects and then append a new key to the objects in the second array?

Consider the following arrays where you are tasked with comparing them and returning a filtered version of array two containing elements found in array one: const array1 = [ { name: "Jack", age: 54, title: "IT Engineer" }, { na ...

Designing a login system with MEAN stack architecture?

I am currently in the process of building a web application using the MEAN stack (MongoDB, Express, AngularJS, and node.js). Specifically, I am working on implementing a login system and securing certain routes in my Angular app so that they are only acces ...

Troubleshooting Loading Problems in React Native Using Geny Motion

Currently utilizing react native Using react-native-cli version 2.0.1 and react-native version 0.55.3 Execution was done through react-native run-android Encountering a perpetual loading screen while running the app in debugger mode, with 127.0.0.1:8081 ...

What is the best way to retrieve scope variables from multiple directives?

I am working on a directive that represents a person with changing location attributes. My goal is to access all the locations together and plot them on a map using the angular-leaflet-directive. I'm struggling to figure out how to access these variab ...

limit mongoose search results to a specific year

Would it be possible to add an option for the api user to filter the wine query by year? However, if no year is specified, mongoose should not return an empty array. The same applies to the price property. For example, http://localhost:1234/api/wine?year= ...