What type of Javascript is required for a photo carousel that displays random images from a designated folder?

I have a minor issue that has been keeping me up at night. I can't seem to shake it off and find the right solution!

Currently, I am working with Bootstrap 4 as my Framework. My task is to create a full-page Carousel that cycles through images randomly each time the page is refreshed, without any user interaction. The images need to be fetched from a specific folder due to the large quantity of images available.

Is there anyone willing to assist me with the necessary JavaScript code to achieve this?

Below is a basic piece of code that serves as my starting point. While it works perfectly fine in its current form, the issue arises from the fact that it always displays the same images in the specified order.

Thank you in advance for your help.

<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="beddd0d0dbdcdbe9deddc9b6bcd6dec3">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link rel="stylesheet" href="style.css" type="text/css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Big+Shoulders+Stencil+Text&family=Big+Shoulders+Text&family=Goldman&family=Heebo&family=Quicksand&family=Shadows+Into+Light&display=swap" rel="stylesheet">
    <style media="screen">
        .carousel-inner > .carousel-item {
            min-height: 800px;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }
    </style>
    <title></title>
</head>
<body>
    <section class="nopadding">
        <div id="carouselProjRec" class="carousel slide carousel-fade" data-ride="carousel" interval="1800">
          <div class="carousel-inner">
                <div class="carousel-item transparent" style="background-image: url(img/car4.jpg)">
                </div>
                <div class="carousel-item active transparent" style="background-image: url(img/car3.jpg)">
                </div>
                <div class="carousel-item transparent" style="background-image: url(img/car8.jpg)">
                </div>
                <div class="carousel-item transparent" style="background-image: url(img/car7.jpg)">
                </div>
                <div class="carousel-item transparent" style="background-image: url(img/car6.jpg)">
                </div>
                <div class="carousel-item transparent" style="background-image: url(img/car11.jpg)">
                </div>
            </div>
          </div>
    </section>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8cac7c7dcdbdcdac9d8e89c869d869b">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9a9b6a9a9bcabf7b3aa99e8f7e8eff7e9">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>

Answer №1

Unfortunately, JavaScript does not have the capability to read data from a directory. To achieve this functionality, you would need to utilize a server-side language such as PHP or Node JS to access the directory contents and display them in HTML.

For instance, if you opt for PHP, you can refer to resources like List all files in one directory PHP. This will allow you to create an array of file names:

<?php
  foreach($files as $file) {
    echo '<div class="carousel-item transparent" style="background-image: url(img/' . $file . ')"></div>';
  }

If you decide to go with Node JS, the process is similarly straightforward:

const directoryPath = path.join(__dirname, 'Documents');
fs.readdir(directoryPath, function (err, files) {
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    } 
    files.forEach(function (file) {
       console.log('<div class="carousel-item transparent" style="background-image: url(img/' + file + ')"></div>'); 
    });
});

In conclusion, utilizing a server-side language is essential for achieving this functionality.

Answer №2

Success! The JavaScript is functioning properly.

<div class="container-fluid nopadding" style="width:100vw; min-height: 400px;">

<script language="javascript">
  var delay=1500 //set delay in miliseconds
  var curindex=0

  var randomimages=new Array()

    randomimages[0]="img/car1.jpg"
    randomimages[1]="img/car5.jpg"
    randomimages[2]="img/car2.jpg"
    randomimages[3]="img/car4.jpg"
    randomimages[4]="img/car3.jpg"
    randomimages[5]="img/car6.jpg"

  var preload=new Array()

  for (n=0;n<randomimages.length;n++)
  {
    preload[n]=new Image()
    preload[n].src=randomimages[n]
  }

  document.write('<img width="100%" height="100%" class="img-size" <img name="defaultimage" src="'+randomimages[Math.floor(Math.random()*(randomimages.length))]+'">')

  function rotateimage()
  {

  if (curindex==(tempindex=Math.floor(Math.random()*(randomimages.length)))){
  curindex=curindex==0? 1 : curindex-1
  }
  else
  curindex=tempindex

    document.images.defaultimage.src=randomimages[curindex]
  }

  setInterval("rotateimage()",delay)

</script>

 <!--  Random image slideshow - Thanks to Tyler Clarke (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ea9e93868f98aa83828b9e8f89858c8c8f8fc4898587">[email protected]</a>)
  For this script and more, visit http://www.javascriptkit.com -->

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

How to easily open a search page with just a click on the search field in CodeIgniter?

I am in the process of implementing a search feature in CodeIgniter. My view file is divided into two main sections: Header section, which includes the search bar <?php echo form_open('controller/live_search');?> <div class="toolba ...

"Transforming Selections in Illustrator through Scripting: A Step-by-Step Guide

In Illustrator, I successfully used an ExtendScript Toolkit JavaScript code to select multiple elements like text, paths, and symbols across different layers. Now, I am looking to resize them uniformly and then reposition them together. While I can apply ...

What are the benefits of incorporating CSS into a CSS block rather than utilizing inline output with HtmlHelper in CakePHP?

Just a few days ago, I embarked on the journey of learning CakePHP through their blog tutorial. Now, I am diving into writing my own small project to gain hands-on experience with the framework. After going through their documentation, I discovered two ...

How can I show the configuration in Laravel?

After updating my pages to utilize an extended header for consistent content across all pages, I encountered an issue with the footer configuration. Whenever I attempt to retrieve a configuration from Laravel, it appears as normal text instead of being pro ...

What causes the while loop in a threejs render function to not refresh each frame?

I'm struggling with handling an array of 8 cubes, each only 1 pixel tall. When a button is pressed, I want them to smoothly animate to a new height using a while loop. Here's my current implementation: if (buttonPressed) { console.log(' ...

Changing divider color in Material-UI with React

I need some assistance with changing the color of the divider component from the material ui framework. I have successfully changed colors for other components using the useStyles() method like this: const useStyles = makeStyles(theme => ({ textPad ...

What are the steps to generate an npm package along with definition files?

Is it possible to create an NPM package with definition files containing only interfaces declared in *.ts files? Consider a scenario where we have two interfaces and one class definition: export interface A { id: number; } export interface B { name: s ...

Struggling with getting Bootstrap Affix-bottom to scroll back up?

Despite reading various answers, I am still struggling to configure the settings correctly. The columns header is not resuming scrolling upwards as expected. Below is my PHP code snippet: <div id="columnsHeader" class="affix" data-offset-top="800" da ...

Utilizing Airbnb's iCalendar Link for Automation

I have obtained the iCalendar link for an Airbnb listing. Upon visiting the link in any browser, it automatically triggers the download of a .ics iCalendar file. My goal is to develop an application that can sync with this specific Airbnb listing's iC ...

Create a variety of colors with a simple click

A form has been created for the footer where clicking on an input causes the text and border-bottom to transition from grey to white. Visit Code Pen HTML: <div class="footer"> <div class="footerContainer"> <form> <inp ...

Using jQuery and JavaScript to swap images depending on the option chosen in a dropdown menu

On my existing ecommerce website, I have a dropdown menu with the following code: <select data-optgroup="10201" class="prodoption detailprodoption" onchange="updateoptimage(0,0)" name="optn0" id="optn0x0" size="1"><option value="">Please Selec ...

Presentation Slider (HTML, CSS, JavaScript)

Embarking on my journey of creating webpages, I am eager to replicate the Windows 10 start UI and its browser animations. However, my lack of JavaScript knowledge presents a challenge. Any help in reviewing my code for potential issues would be greatly app ...

There was a failure to retrieve any data when trying to send an ajax request to

When attempting to send JSON data to my PHP, I am not receiving any response when accessing it in my PHP code. Below is the Ajax request being made: var project = {project:"A"}; var dataPost = JSON.stringify(project); $.ajax({ url: 'fetchDate.p ...

Encountering issues with scope: Unable to retrieve value and receiving an error message stating 'Cannot assign value to undefined property'

var mainApp = angular.module("Main", []); mainApp.controller("CtrlMain", [ function ($scope) { $scope.amount = 545 }]);` var app = angular.module("Main", []); app.controller("MainCtrl", [ function ($scope) { $scope.value = 545 ...

"Trouble arose when I tried to incorporate additional functions into my JavaScript code; my prompt feature is not

As a beginner in HTML and JS coding, I am working on creating a page that prompts user input for a name and then executes animations using radio buttons. However, after adding functions for radio button changes, my prompt is no longer functioning properly. ...

"Implementing a monorepo with turborepo for seamless deployment on Vercel: A step-by-step

There has been recent news about Turborepo being acquired by Vercel, sparking my interest to dive into it. To start, I initiated a turbo repo project with the following command: pnpx create-turbo Afterwards, I attempted to deploy it on Vercel by referring ...

Why is my jQuery $.ajax success function not providing any results?

When checking the Network tab in Chrome, I noticed that the correct data (action, username, password) is being sent, but the message is not returning to $('#return_login'). Can anyone spot what might be wrong with my code? Below is the jQuery co ...

Adjust the dimensions of the react-dropdown-tree-select element to better fit your needs

Hey there, I'm a beginner web developer currently working on a tree-based dropdown menu. Check out the documentation here To see it live in action, visit the example here I'm trying to adjust the height and width of the "Search/DropDown bar" in ...

XMLHttpRequest Error: The elusive 404 code appears despite the existence of the file

This is the organization of my project files: The folders Voice, Text, and Template are included. https://i.stack.imgur.com/9un9X.png When I execute python app.py and navigate to localhost http://0.0.0.0:8080/, the index.html page is displayed with conte ...

The hover effect is not functioning upon loading

Demo: http://jsbin.com/afixay/3/edit 1) Hover over the red box. 2) Without moving the cursor, press ctrl+r to reload the page. 3) No alert will appear. However, an alert will pop up once you move the cursor away and hover back over the box. The issue h ...