Place an arbitrary <IMG> element within a div and assign it a specific class

I have a series of images that are transitioned between using JavaScript code.

The currently displayed image is given the "active" class.

Is there a way to assign the "active" class randomly to one of the images so that it doesn't always start from the same point when the page loads?

<div id="quote">
    <img class="active" src="http://dicktyler.com/dev/images/quote1.png" />
    <img src="http://dicktyler.com/dev/images/quote2.png" />
    <img src="http://dicktyler.com/dev/images/quote3.png" />
    <img src="http://dicktyler.com/dev/images/quote4.png" />
</div>

Answer №1

Here's a way to achieve the desired outcome:

let images = $('#gallery img');
let randomNumber = Math.floor(Math.random() * images.length);
images.eq(randomNumber).addClass('highlighted');

Check out this JSFiddle Demo

This code snippet will create a random number between 0 and the total number of images in the gallery, which is 7 for example. We then use the eq() method to select the image based on the randomly generated number.

Answer №2

To easily achieve this task, you can start by selecting all the img elements and storing them in a jQuery object. Then, use the eq method to pick a specific image from the collection. To determine which image to select with eq, generate a random number using Math.random() * $imgs.length. This will provide a number ranging from 0 to one less than the total count of images available.

var $imgs = $('#quote img');

$imgs.eq(Math.floor(Math.random() * $imgs.length)).addClass('active');

Answer №3

My Approach:

To start, I would tally up the number of images present on the page.

total_images = $('#quote img').length;

Next, I'd generate a random number within the range of 0 to the total count of images.

random_num = Math.random() * (total_images - 0) + 0;

Once that is done, I would designate the active class to the image selected as a child of #quote.

$('#quote img:nth-child(random_num)').addClass('active');

For flexibility, I'd convert this process into a function:

function applyRandomImage(div){
    total_images = $('#'+div+' img').length;
    random_num = Math.random() * (total_images - 0) + 0;
    $('#'+div+' img:nth-child(random_num)').addClass('active');
}

Finally, I would trigger this function by calling it with the appropriate div ID:

applyRandomImage('your_div_id');

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

What is the significance of including the *dispatch* variable in the *dependency array* for the useEffect function?

While reviewing the source code of a ReactJS project, I noticed that the dispatch variable is included in the dependency array of the useEffect hook. Typically, I'm familiar with including useState() variables in this context, so I am curious about th ...

Vuetify's offset feature seems to be malfunctioning as it does not

I'm facing an issue with the <v-flex> element in my code, specifically with the offset property not responding as expected. Despite following the recommended layout from the vuetify docs, I can't seem to get it right. Below you can see the ...

Guide on how to align the bootstrap popover's arrow tip with a text field using CSS and jQuery

I have tried multiple solutions from various questions on Stack Overflow, but I am still struggling to position the arrow tip of the bootstrap popover correctly. html: <input type = "text" id="account_create"/> js: $('.popov ...

A guide on incorporating ":host" (or ":host()") with ":has()"

Is there a way to properly use :host (or :host()) with :has() ? For instance, like the following code snippets: :host:has([disabled]) { opacity: 0.75; } or :host(:has([disabled])) { opacity: 0.75; } Unfortunately, the opacity value doesn't seem ...

Creating a full width and height slider with a header menu that is responsive to all device screen sizes

Looking to create a full-width slider with a header that adjusts for all screen sizes, especially larger devices. I've been searching online but haven't found a satisfactory solution yet. If anyone has any ideas or tips on how to achieve this, pl ...

Implementing gridlines on a webpage using HTML and JavaScript to mimic the grid layout found in Visual Studios

Currently, I have a grid snap function in place, however, I am looking to add light grey lines horizontally and vertically on my Designing application. The goal is to achieve a similar aesthetic to Visual Studios' form designing feature. Utilizing so ...

Issue with specific selectors causing React CSS module malfunction

Currently, I am a beginner in learning React and have been experimenting with CSS modules. Even though Menu.module.css is mostly functioning correctly, it seems to be having an issue applying styles to the .menu a.last selector for some reason (although i ...

Encountering issues with installing Angular using npm due to errors

When I run npm install, I encounter errors. Though I can get it to work by using npm install --force, I prefer not to rely on the force flag. After reading through the errors, it seems like there might be a version compatibility issue, but I'm having ...

Creating responsive sections in Bootstrap with varying heights based on screen size

While working on a website using bootstrap, I've encountered an issue with the spacing between text and the end of sections on large screens, as well as text running off sections on smaller screens. Each section has a set height in the CSS that may be ...

Using React.render to render an empty subcomponent within a jsdom environment

Experimenting with React in node using jsdom has been an interesting challenge for me. I encountered an issue when attempting to render a component that includes another component with content, only to have the subcomponent's content fail to render. F ...

Place centered items within a flexbox that uses space-between alignment

When designing a navigation section, I am looking to achieve space-between justification. However, for smaller screens where the navigation items may need to wrap onto multiple rows, I want the items to center themselves instead of aligning to the left whe ...

What is the process for exporting Three.js files to .stl format for use in 3D printing?

I stumbled upon a page with this link: Is it possible to convert Three.js to .stl for 3D printing? var exporter = new THREE.STLExporter(); var str = exporter.parse(scene); console.log(str); However, despite using the code provided, I am unable to export ...

Does the height of the rendered font adjust based on the length of words in Japanese formatting?

I can't figure out why this strange issue is occurring... It seems that the font "size" (or rather, the height it occupies) changes depending on the length of a word. I tried to reproduce this in English without success, but it consistently happens w ...

Accelerate blinking timer by utilizing CSS3 animations

I'm currently developing a quiz application that includes a timer counting down from 10 seconds to 0 seconds. As the timer reaches closer to 0 seconds, I am looking to implement a feature where my text blinks faster and faster. Additionally, I would l ...

What methods can be used to extend the distance measurement with the help of Google Maps

I've searched online for the answer, but still haven't found it. I'm currently developing a website where users can search and select a location using the Google Geocoding API. Once the user chooses a place, I retrieve its bounds, but then ...

What is the best way to display the output of a Node function in HTML or console?

I am a beginner with node.js and I'm working on printing results to the console and eventually displaying them in HTML. I attempted to invoke the function as a variable that could be used later in HTML, but it was not successful. Below is an example o ...

Tips for modifying CSS based on the user's Operating System

Is there a way to write CSS that produces different effects on Mac OS compared to other operating systems? For example: .(mac){ height: 100%; width: 100%; overflow: hidden; } .(win and linux){ height: 100%; width: 100%; ...

Animating range tick movements as the range thumb moves

My custom range input includes a span that displays the range's value and a div with multiple p elements acting as ticks. To create these ticks, I had to use a custom div because using "appearance: none" on the range hides the ticks by default. The ti ...

The presence of the 'absolute' attribute on an element disrupts the smooth fading

I am encountering an issue where the text I am trying to fade just suddenly jumps to its final state without any smooth transition in between, and there is also a delay. I have been using CSS properties like opacity: 0/1 and transform: opacity for the fa ...

Step-by-Step Guide: Exporting a div to a beautifully formatted PDF with NextJs

Currently, I am working on an app project that involves filling out forms and having the information automatically formatted into a div to generate CLP labels. My goal is to be able to export this div in pdf format while also being able to select sizes ran ...