Unique background images will be assigned to each individual class instance randomly

In my project, I have implemented a Sass function that returns a random URL from a specific set of URLs. Here is how the function looks:

@function randomUrl(){
    $images: (
    "/images/watermarks/area-watermark.png",
    "/images/watermarks/bar-watermark.png",
    "/images/watermarks/line-watermark.png",   
     $img: nth($images, random(length($images)));     
     @return $img;
}

Currently, I am applying this function to a CSS class like this:

.myClass{
 background-image: url(randomUrl());
}

However, my goal is to have a different random image for each instance of the "myClass" class. For example, if there are 10 divs with the class "myClass" in my HTML, I want each div to display a unique background image. Unfortunately, my current implementation only shows one random image that gets repeated in all the divs whenever I compile the code.

Answer №1

The built-in function known as random() serves the purpose of generating a random number within a specified range. It's important to note that each time this function is called, there is no guarantee that the numbers produced will be unique due to the nature of randomness.

If your goal is to shuffle a list, it can be challenging as Sass does not offer a native shuffling function. However, third-party libraries like the following can help achieve this:

The code implementation in both these libraries is quite similar, such as the one extracted from the 'randomize' library:

@function shuffle($list) { 
  $list-length: length($list);

  @while($list-length > 0) {
    $rand: random($list-length);
    $temp: nth($list, $rand);
    $list: set-nth($list, $rand, nth($list, $list-length));
    $list: set-nth($list, $list-length, $temp);
    $list-length: $list-length - 1;
  }

  @return $list;
}

For those looking to avoid list iteration, they could opt for a structured approach like this:

@import "ExampleLibrary";

$last-pos: 0;
$items: example-shuffle(
  "/images/item1.png"
  "/images/item2.png"
  "/images/item3.png");

@function randomItem(){
  $last-pos: if($last-pos == length($items), 1, $last-pos + 1) !global;
  @return nth($items, $last-pos);
}

.myCustomClass {
  background-image: url(randomItem());
}

.myCustomClass {
  background-image: url(randomItem());
}

.myCustomClass {
  background-image: url(randomItem());
}

Output:

.myCustomClass {
  background-image: url("/images/item3.png");
}

.myCustomClass {
  background-image: url("/images/item1.png");
}

.myCustomClass {
  background-image: url("/images/item2.png");
}

An alternative suggestion would be to utilize list iteration for a more straightforward solution:

@import "ThirdPartyLibrary";

$items: thirdparty-shuffle(
  "/images/item1.png"
  "/images/item2.png"
  "/images/item3.png");

@for $i from 1 through length($items) {
  .custom-#{$i} {
    background-image: url(nth($items, $i));
  }
}

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

Height of video isn't increasing

Since moving my website to a new domain, I've noticed that the video on my NEW About Us page is shrinking for some reason. It seems like the div holding the iframe is not expanding beyond 181px. When it does grow, the video adjusts itself and expands ...

Exploring the capabilities of React Native, I experimented with utilizing flexbox to align two

When using the code below <View style={{flexDirection: "row", justifyContent: "space-between"}}> <View> <Text style={{fontSize: 50}}>{hours}</Text> <Text style={{alignSelf: "flex-end"}}>h</Text> <Text s ...

Performing PHP MySQL table database insertion utilizing the $_GET approach using Codeigniter-3 and Dropzone-4.1 plugin

Currently working with CodeIgniter 3 and running into an issue with "id_case" showing as undefined index. When I click a link in index.php: <?php echo "<td><a href='/ci_dropzone/?id_case=".$row['id_case']."'>Upload File ...

Employing PHP for the purpose of updating the content within a <div> element solely when the submit button of a <form> is clicked

I have a unique issue with my website structure. I have an 'index' page that dynamically replaces the content of 'mainContents' when any button in the navigation bar is clicked. The purpose of this design is to reload only the necessar ...

Guidance on implementing fallback font formats using FontFace API

I am exploring the FontFace API (not @fontface) and wondering if there is an easy way to include multiple font formats, similar to providing multiple sources in @fontface. Alternatively, is there a simple method to identify which font formats are supporte ...

Why is it that vanilla HTML/JS (including React) opts for camelCase in its styling conventions, while CSS does not follow the same pattern

Each type of technology for styling has its own set of conventions when it comes to naming properties, with camelCase and hyphenated-style being the two main options. When applying styles directly to an HTML DOM Node using JavaScript, the syntax would be ...

I'm looking to add some borders to my image using bootstrap/CSS - does anyone know how this can be achieved

I have designed the UI, but I'm struggling to create the border effect shown in the image below: https://i.sstatic.net/Jdp17.png <div> <img class='image1' src='https://www.w3schools.com/w3css/img_lights.jpg' /> ...

JQuery Tic Tac Toe Duel: Face Off Against Your Friend in a Thr

Looking for some advice here. I'm new to game development and currently working on a 2 Player Tic Tac Toe game. I need help with implementing the game functionality. Any suggestions? I want to disable the "div" once a player clicks on it, but I' ...

The Jquery code for Fullpage.js is causing unexpected behavior on the HTML page

While following a tutorial at the given link, I encountered an issue. Around the 9:08 mark, the instructor adds some JavaScript and demonstrates that fullpage.js is working. However, when I refresh the page after implementing the new code, it doesn't ...

Is there a way to eliminate this pesky margin?

please check out this: https://jsfiddle.net/desytec/73qdtejg/1/#&togetherjs=w3lvLQi0v6 This displays the following table definition: <table id="semana" class="table table-striped dt-responsive table-bordered display ...

Formatting tables

Below is the table structure that I have. I attempted to insert empty tds divs in order to achieve the formatting shown in the image, but I have not been successful. Any suggestions or ideas would be greatly appreciated. <table border="0" cellpadding=" ...

When the class name is hovered over, apply the specific style to the element

When I hover over my card(box), I want the description text to move up 10px like shown in the pictures. However, the city name text and button also shift for some reason. View card without hover (IMG) Here is with hover effect (IMG) In the second image, ...

Simple math operations in GWT CssResource

I need help achieving a similar result to the following: // design.css @define borderThickness '2px'; .format { width: borderThickness + 2; height: borderThickness + 2; } The desired output is for the width and height properties to equal 4 ...

Clickable tab to collapse a section containing an image and aligned text

When using Bootstrap 3, I have a button that collapses a div containing an image and text. The button alternates between showing a '+ More' and a '- Less' message. However, the alignment of the image is off with the text. Is there a way ...

What steps can I take to prevent my menu items from overlapping in the mobile navigation menu?

I am currently working on creating a mobile menu, but I'm facing an issue where the menu items overlap when hovered over. Instead, I want the menu items to move downwards when hovered upon to prevent the text from overlapping. Below is the HTML code ...

Issues with Bootstrap Carousel Slide Show functionality in FireFox

I have implemented a Bootstrap-5 Carousel Slide Show for the website banner. It is functioning correctly in Google Chrome, but there seems to be an issue when viewed in Firefox. The Firefox browser version I am using is 90.0.2 (64-bit). Upon inspecting the ...

I'm having trouble getting a CSS transition to work on a PNG sequence using jQuery in Mozilla

For my latest project, I decided to create an animation using a PNG sprite sequence. The idea was to add a smooth transition effect on hover and have the animation play in reverse when the hover state ends. If you want to take a look at the code yourself, ...

What is the best way to set the width of an iframe within a <td> element to be 33% of the screen?

I am facing an issue with scaling an iframe dynamically inside a <td> element. My goal is to make the iframe occupy 33% of the screen width while automatically adjusting its height. Here is what I have tried: <iframe src="google drive presentati ...

Showing a section of a DIV inside an iframe

I have implemented an HTML object in the following way: <object id="foo" name="foo" type="text/html" data="mypage.aspx"> </object> However, I do not want to display the entire content of mypage.aspx within the HTML object/iframe. In ...

Experiencing challenges working with the offset class in Bootstrap 4

Recently, I attempted to use offset in my form rows and columns to center them using Bootstrap 4 documentation. Unfortunately, it didn't work as intended and now I'm stuck trying to figure out the problem. Despite looking for similar issues onlin ...