Difficulty encountered while implementing a carousel using HTML, CSS, and JavaScript

I'm currently working on creating a carousel using only HTML, CSS, and JS.

While it is functional, it does not perform as smoothly as I had anticipated.

After completing one full round of images, there is an approximate 8-second delay before it starts displaying the images from the beginning again, pausing intermittently.

Moreover, the div containing the background images is set to 100% width and 100vh height. Despite my efforts to adjust properties like bg-repeat, bg-size, and bg-position, I am unable to achieve the desired display on the screen - the images either get cropped with background-size: cover, or appear too small with background-size: contain or other settings.

Can someone please review this "working" demo for me? Thank you.


var divi = document.querySelector(".divi");
srcArr = ["https://picsum.photos/id/237/200/300", "https://picsum.photos/id/238/200/300", "https://picsum.photos/id/239/200/300", "https://picsum.photos/id/240/200/300"];
var iter = 0;

setInterval(function() {
  if (iter == (srcArr.length)) {
    iter = 0;
  } else {
    divi.style.backgroundImage = "url('" + srcArr[iter] + "')";
    iter++;
  }
}, 4000);
      

* {
  padding: 0;
  margin: 0
}

.divi {
  width: 100%;
  height: 100vh;
  background-image: url("https://picsum.photos/id/240/200/300");
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  background-size: cover;
}
      
<div class="divi"></div>

Answer №1

In the words of Tyler Roper, once the iteration reaches the length of the source array, it resets to zero without changing the image, causing a delay of 4 seconds before moving on to the next image.

const
  divi   = document.querySelector(".divi"),
  srcArr = ["https://picsum.photos/id/237/200/300", "https://picsum.photos/id/238/200/300", "https://picsum.photos/id/239/200/300", "https://picsum.photos/id/240/200/300"];
var iter = -1;

setInterval(function() {
  iter = (iter + 1) % srcArr.length;
  divi.style.backgroundImage = "url('" + srcArr[iter] + "')";
}, 4000);
* {
  padding: 0;
  margin: 0
}

.divi {
  width: 100%;
  height: 100vh;
  background-image: url("https://picsum.photos/id/240/200/300");
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  background-size: cover;
}
<div class="divi"></div>

Answer №2

Every four seconds, there is a check using an if statement. If the condition evaluates to false, the image is changed. However, if it evaluates to true, it requires two additional iterations to continue, resulting in a delay of 8 seconds.

Personally, I find it more efficient to encapsulate such logic in functions and utilize a recurring setTimeout function instead of a setInterval. I have also included a return statement for the timeout in case you need to stop the slideshow at any point.

Regarding the background styling, I have initially set background-position: center;.

const divi = document.querySelector(".divi");
const srcArr = ["https://picsum.photos/id/237/200/300","https://picsum.photos/id/238/200/300","https://picsum.photos/id/239/200/300", "https://picsum.photos/id/240/200/300"];
const timer = 1000;

const nextImg = (imageArray, index) => {
  divi.style.backgroundImage = `url('${imageArray[index]}')`;
  index = ++index % imageArray.length;
  return setTimeout(()=>nextImg(imageArray, index), timer);
};

const startSlideshow = imageArray => nextImg(imageArray,0); 

//Start slideshow
const slideshow = startSlideshow(srcArr);

//Stop slideshow
//clearTimeout(slideshow);
* {
  padding: 0;
  margin: 0
}

.divi {
  width: 100%;
  height: 100vh;
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  background-size: cover;
  background-position: center;
}
<div class="divi"></div>

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

Error encountered with structured array of objects in React Typescript

What is the reason for typescript warning me about this specific line of code? <TimeSlots hours={[{ dayIndex: 1, day: 'monday', }]}/> Can you please explain how I can define a type in JSX? ...

Using Knockoutjs to fetch and display server-side data within the MVC framework

My goal is to initialize my knockoutjs viewmodel with data from the server. In my ASP.Net MVC project, I achieve this by passing a mvc viewmodel to the view: public ActionResult Edit(int cvId) { CV cv = repository.FindCV(cvId); //auto mapper mapp ...

The Distinction Between "Q" and "q" in AngularJS and RequireJS

Currently, my project involves developing a single page application using AngularJS, Breeze, and RequireJS. While trying to configure AMD with requirejs to integrate Angular and Breeze, I ran into an issue related to Breeze's dependency on "q". Intere ...

Problem with locating elements using Selenium xpath

While using selenium and xpath, I encountered a peculiar issue. On a page, there are 25 <a> tags with nested <img/> tags. I am trying to retrieve all these elements using the findElements() method. Interestingly, upon inspecting the page source ...

In my Ionic/Angular project, I'm attempting to showcase two columns side by side in a row. However, the layout seems to be stacking them on top of each other with the

I am having some trouble arranging two columns in a row for my Ionic/Angular project. It seems like the content is stacking on top of each other instead of side by side. Here's the CSS I'm using: <ion-grid class="rewards-container&q ...

Retrieving JQuery Results Based on List Items

Once I have obtained the list id from the navigation, my next step is to send the id to a PHP file that will return a JSON list. Below is the jQuery syntax I am using: $("#ul_navigation li").click(function(e) { idsec = this.id; alert(idse ...

Exploring the wonders of retrieving JSON data in PHP through an Ajax request

A front-end developer is sending an array of data formatted as a JSON object using an Ajax call. The JSON object structure is shown below: { "name": " Test Name ", "image_url": "test URL", "include": [ "1" ], "dimension": [ null ], "media_type" ...

Selecting the initial and final elements in a list without utilizing pseudo-classes

Currently, I am in the process of designing a custom MUI styled component and I have encountered a challenge. I want to apply extra styles specifically for the first and last child elements. The issue arises because MUI utilizes the emotion styled library, ...

Mapping an array in ReactJS based on the specific order of another array

In my experience with Unmitigated, the answer proved beneficial. If you're arriving from a Google search, please scroll down for more information. Order: [ "567", "645", "852", "645", "852", "852 ...

Utilizing BeautifulSoup to Extract Links

Currently, I am extracting cricket schedules from a specific website using Python's Beatiful Soup library. The webpage I am scraping corresponds to the following URL: www.ecb.c0.uk/stats/fixtures-results?m=1&y=2016 This particular link displays ...

How come my counter is still at 0 even though I incremented it within the loop?

Within my HTML file, the code snippet below is present: <div id="userCount" class="number count-to" data-from="0" data-to="" data-speed="1000" data-fresh-interval="20"></div> In my Ja ...

Traverse through the keys and values of a JSON object using JavaScript

I have a json string that needs to be parsed in a specific way. The structure of the json is as follows: { "a": [{ "b": [ ["c"], [] ], "d": [ [], [] ], "e": [ [], ["f"] ], "g": [ [], ...

Tips for extracting the two characters following a space in a string with or without the use of regex

How can I extract only the initials of 2 characters after spaces? See the code snippet below: const name = "John Peter Don"; const result = name.match(/\b(\w)/g).join(''); console.log(result)// JPD->> i want only JP ...

My component reference seems to have gone missing in angular2

Trying to load my Angular 2 app, I encountered this error: https://i.stack.imgur.com/FmgZE.png Despite having all the necessary files in place. https://i.stack.imgur.com/kj9cP.png Any suggestions on how to resolve this issue? Here is a snippet from ap ...

Modifying JavaScript prototypes on the fly can lead to troublesome issues

My curiosity has been piqued by the concept of dynamically changing a constructor's prototype in JavaScript, leading me to the findings above. It appears that an already constructed instance does not inherit the properties of the newly changed protot ...

Sliding panels with Jquery

I've created some basic panels that slide in and out horizontally. My goal is to hide all content except the first panel when the page loads. When a link to other panels is clicked, the current content will slide left to be hidden and new content will ...

What is the process for setting up basic http authorization using angular.js?

My backend setup follows a structure similar to what is explained in this article. I am looking to make a GET request using angular.js, just like curl does it, with authorization via HTTP headers: $ curl -u miguel:python -i -X GET http://127.0.0.1:5000/a ...

Before each existing DIV in a loop, a new div is inserted using the insertBefore

const len = document.getElementById('parent').children.length for (let i = 0; i < len; i++) { const div = document.createElement("div"); document.getElementById('parent').insertBefore(div, document.getElementById('parent' ...

Bootstrap does not support horizontal alignment of columns

I can't seem to get my columns to align horizontally in bootstrap. I want the image on the left and the text on the right, but they keep stacking vertically. Can someone help me with this? As far as I know, col-md-6 should divide the page into 2 colu ...

In Mobile View, I want to swap out my current image for text to keep it hidden

I am attempting to include text that is only visible in Mobile View as a replacement for my logo. Below is the code I am using: CSS: @media only screen and (max-width:1024px) { header .logo { display: none; } header .logo a { display: non ...