What is the best way to shuffle the displayed images on a website to make the order random?

I'm looking to create a unique collage using 10 image files in a folder with vanilla JS. The goal is to randomize the images within a Bootstrap container on a website while maintaining their aspect ratio by utilizing a grid layout. However, I've been struggling to find a solution for randomly placing the images inside the container.

While searching, I came across an example that involves uploading files here.

Here's an example of how the HTML code may look:

<div class="container">
    <div class="masonry">
        <div class="masonry-item">
            <img class="masonry-content " src="./images/Gallery/001.JPG" />
        </div>
        <div class="masonry-item">
            <img class="masonry-content " src="./images/Gallery/002.JPG" />
        </div>
        <div class="masonry-item">
            <img class="masonry-content " src="./images/Gallery/009.JPG" />
        </div>
    </div>
</div>

And here are some functions used in JavaScript to handle resizing and positioning the items:

// JavaScript Functions
function resizeMasonryItem(item){
   // function details here...
}

function resizeAllMasonryItems(){
    // function details here...
}

function waitForImages() {
    // function details here...
}

var masonryEvents = ['load', 'resize'];
masonryEvents.forEach( function(event) {
    window.addEventListener(event, resizeAllMasonryItems);
} );

// CSS styling
.masonry {
    display: grid;
    grid-gap: 10px;
    grid-template-columns: repeat(auto-fill, minmax(200px,1fr));
    grid-auto-rows: 0;
}

.masonry-item {
    border-radius: 5px;
    // additional CSS properties...

}

Answer №1

To create a dynamic image gallery, start by organizing the image URLs into an array. Next, generate another array with numbers ranging from 0 to N-1 to act as index values for accessing the images. Utilize a shuffle function like the following:

function randomSort(indices) {
  indices.sort(() => Math.random() - 0.5);
}

After shuffling the index list, use these randomized indices to retrieve the src attribute from the images array. This attribute can then be assigned to the specified HTML (bootstrap) elements to display your shuffled image gallery.

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

Transferring data as a JSON object from PHP to JavaScript

My PHP file is named page.php <?php $php_variable = $_GET['param1']; $uv = str_replace("{ZIP Code}", $php_variable,'http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/{ZIP Code}/JSON'); $homepage = file_get_contents($u ...

Aligning images in center of list

I'm in need of some CSS expertise to assist with this layout. Here is the current structure: <div class="movieList"> <div class="image" selected = true> <img class="poster" src="image1" selected = true/> </div> <d ...

What is the best method for eliminating underscores from text that is hyperlinked in a locally hosted HTML file?

I recently encountered an issue with my HTML file where the text "Indian" became underlined after saving the file. Here is the code snippet: <a href="file:///G:\work files\project\indian.html" target="_blank"> <div class="button ...

Transfer photos and videos to an external server using Javascript with Meteor framework

I currently have a meteor application hosted on Digital Ocean. I am considering setting up a dedicated server to store all images and videos separately from the site itself. Whenever a user uploads new media, it will be saved to this separate server. Does ...

Tips for designing scrollable overlay content:

I am currently in the process of building a page inspired by the design of Hello Monday. Right now, I have added static content before implementing the parallax effect and auto-scroll. Here is my progress so far: Check out the Sandbox Link One challenge ...

The animation in an AngularJS directive only functions properly when utilizing $timeout

I can't seem to figure out why the animation is not working as intended in the code below: app.directive('openMenu', ['$animate', '$timeout', function($animate, $timeout) { return { link: function(scope, elem ...

A guide to resizing images for uploading in Node.js using Jimp without the need for refreshing the page

My goal is to resize a file server-side using Jimp before uploading it to Cloudinary in a node.js environment. Here's the controller I'm using: exports.uploadImage = async (req, res) => { if (!req.files) { return res.status(400).json({ m ...

Display dynamic form with database value on click event

Seeking assistance to create a JavaScript function or any other method to address the issue I am facing. Currently, I have a functional pop-up form and a table connected to a database with queries. The pop-up form successfully appears upon clicking, howeve ...

Issue encountered when compiling Vue 3 with TypeScript and Webpack Encore: Vue Router's $route is missing

I've been grappling with setting up vue-router's $route in my shims.vue.d.ts file to avoid getting an error on the this scope. Whenever I try to access this.$route.params.paymentId, I keep receiving a type error: TS2339: Property '$route&apo ...

I am experiencing issues with my Ajax code where it is not successfully sending data to the server and

Can someone help me troubleshoot my PHP AJAX code? I am new to PHP and just getting started with learning AJAX. index.html: <html> <head> <script> function sendmessage(str) { var xmlhttp; if (window.XMLHttpRe ...

Numerous elements positioned absolutely are overlapping

I am working on a website with a unique slide layout design. I am currently focusing on two specific slides: https://i.stack.imgur.com/xngF4.png and https://i.stack.imgur.com/W19tJ.png My goal is to include a button on each individual slide, similar to th ...

Extract the raw text content from nested elements

Working with highlight.js to include a custom CSS code, however, this library automatically adds span tags around the desired text For example: <pre> <code class="language-css hljs" contenteditable="true" id="css-code&quo ...

Begin one lesson, end all others

Looking for help with my expandable list menu that I created using jQuery. Here is the code snippet: $("#menu ul li ul").hide(); $("#menu ul li").click(function() { $(this).find("ul").slideToggle(); }); You can view the fully functional menu on jsFi ...

React JS: How to prevent Yup and Formik error messages from being displayed multiple times upon submission

I have implemented Yup and Formik in my Sign up form to handle validation. My goal is to display specific errors based on the Yup validation rules I've set up. Take a look at the code snippet below: import React from 'react'; import { ...

Send an ajax request to upload several images to the server

I am currently facing an issue with my web application that allows users to create posts with a maximum of 15 images. I have implemented AJAX requests to send all the data, including the images, in one request. However, I encountered this error: An error ...

Creating resizable rows of DIVs using jQuery

I'm currently developing a scheduling widget concept. The main idea is to create a row of DIVs for each day of the week. Every row consists of a set number of time periods represented by DIVs. My goal is to enable the resizing of each DIV by dragging ...

The dark theme in React Material UI will be specifically targeted and applied only to the drawer

I want to implement a dark theme specifically for the drawer component. In Drawer.js <ThemeProvider theme={theme}> <div> {props.token && ( <Drawer anchor="left" open={props.isDrawerOpen} ...

Updating Element Value in Python Using JS and Selenium

Hello, everyone. I'm new to coding and seeking some help regarding a problem I encountered with using 2captcha for my Python web scraping automation. Upon running the script, I receive the captcha token from 2captcha as instructed in their API documen ...

Even when the dimensions are set to 100 width and height, the scroll bar still makes an

I recently embarked on my journey to learn web development by enrolling in a course on Udemy. Currently, I am diving into CSS3/HTML5 and have started a small project involving CSS3 - creating a web page that represents the Universe. My goal is to incorpora ...

Styling in CSS is being applied to a button element within a React component,

Having trouble with a button styled with the className 'actions' The button displays the CSS styling from '.actions', but not '.actions button'. Both should be applied. This code snippet works for all elements ...