Image Carousel Extravaganza

Trying to set up a sequence of autoplaying images has been a bit of a challenge for me. I've attempted various methods but haven't quite nailed it yet. Take a look at what I'm aiming for:

https://i.stack.imgur.com/JlqWk.gif

This is the code snippet that I currently have:

var mItemsCount = $(".home-m-item").length - 1;

setInterval(function() {
  var t = $(".home-m-item.active");
  t.removeClass("active");
  if (t.index() === mItemsCount) {
    $(".home-m-item:first").addClass("active");
  } else {
    t.next().addClass("active");
  }
}, 200);

var windowPathname = window.location.host,
    loader = $(".loader");
.home-m {
    position: relative;
    z-index: 3;
    padding: 0 0 200px;
    background: #111 url(assets/images/home/m-slant-bg.svg) bottom/100% 100% no-repeat;
}
        
        a, a:active, a:focus, a:hover, a:link, a:visited {
    outline: none;
}
        
    .home-m-items {
    position: absolute;
    left: 1px;
    top: 1px;
    width: calc(100% - 2px);
    height: calc(100% - 3px);
    z-index: 1;
}
        
    .home-m-item{
            width: 100%;
            height: 100%;
            positoin: absolute;
            left: 0;
            top: 0;
            background-repeat: no-repeat;
            background-size: cover;
            background-position: 50%;
            visibility: hidden;
    }
        
        .home-m-item.active {visibility:visible}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="home-m">
    <div class="home-m-items">
      <div style="background-image: url('https://rossettibev.wpengine.com/wp-content/uploads/2020/08/R-Image-1.png');" class="home-m-item"></div>
      <div style="background-image: url('https://rossettibev.wpengine.com/wp-content/uploads/2020/08/R-Image-3.png');" class="home-m-item"></div>
      <div style="background-image: url('https://rossettibev.wpengine.com/wp-content/uploads/2020/08/R-Image-3.png');" class="home-m-item"></div>
      <div style="background-image: url('https://rossettibev.wpengine.com/wp-content/uploads/2020/08/R-Image4.png');" class="home-m-item"></div>
      <div style="background-image: url('https://rossettibev.wpengine.com/wp-content/uploads/2020/08/R-Image-5.png');" class="home-m-item"></div>
    </div>
</div>

JavaScript animations are still new territory for me, so I suspect the issue lies within my script. However, I would also appreciate a solution achievable through keyframes.

Answer №1

If you're looking for a solution, here's one approach. You can maintain your current CSS settings, but remove the visibility:hidden property from the item div. However, it's worth noting that your CSS may not be fully responsive. I've included a responsive option below for consideration. To simplify your HTML structure, you can trim it down to the following code snippet. For a visual demonstration, refer to this live demo hosted on CodePen: https://codepen.io/hileamlak/pen/jOqmpmm?editors=1010

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
    
    <div class="home-m">
        <div class="home-m-items">
            <div class="home-m-item"></div>
        </div>
     </div>
</body>
</html>

Your JavaScript:

let imageCounter = 1;

setInterval(
  ()=>{
if (imageCounter>5){imageCounter = 1;}
$(".home-m-item")[0].style.backgroundImage = `url('https://rossettibev.wpengine.com/wp-content/uploads/2020/08/R-Image-${imageCounter}.png')`;
imageCounter++;

},1000)

The provided solution functions correctly in the CodePen live demo reference above. However, using images as background elements could hinder responsive design adjustments based on image dimensions. Here's an alternative suggestion: https://codepen.io/hileamlak/pen/MWymBXV

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

Transform the Standard class into a generic one in typescript

I've created a class that can take JSON objects and transform them into the desired class. Here's the code: import {plainToClass} from "class-transformer"; import UserDto from "../../auth/dto/user.dto"; class JsonConverter { ...

How can I convert an HTML table into a PDF using TCPDF while ensuring that all content is contained within a single div in PHP?

I have successfully converted my JSON API data into an HTML TABLE format and now I am trying to generate a PDF from this HTML TABLE using TCPDF in PHP. Despite trying various methods related to PDF generation using TCPDF, I am facing issues with my code wh ...

An abundant array of options spread across numerous dropdown menus

I have been tasked by a client to do something new that I haven't done before, so I am seeking the best approach. The project involves creating a form with three dropdown menus where users can select from thousands of options. For instance: Users mu ...

Creating an array of data from JSON using JavaScript and displaying it in a chart using ApexChart

I am attempting to generate a chart displaying the value of Bitcoin in Euro. The data is fetched from JSON and converted into an array for the ApexChart series data (ApexData['xbtToEuro']) along with a list of dates. Despite my console indicatin ...

Error: Unexpected syntax error occurred due to the use of '===' operator

Click here for image descriptionError: There is a syntax error in line 7 of the file add.php Code: <?php require_once('db.php'); if ( !empty($_POST['name']) &&!empty($_POST['alias']) &&!empty($_POST[&apo ...

Using useRef to update the input value

I utilized the useRef hook from React to capture an element. When I use console.log(this.inputRef), I receive this output: <input aria-invalid="false" autocomplete="off" class="MuiInputBase-input-409 MuiInput-input-394" placeholder="Type ItemCode or ...

What is the best way to implement CSS Background-size: cover; while also making room for a menu?

Recently, I came across the CSS property background-size: cover, but I encountered a problem. I want the area behind my navigation on the left to be black. However, when I leave black space in the image itself, it gets cropped off when the image resizes. ...

Formatting specific elements within an array

I am working with an array of names, some of which are repeated. These names are then split in half and displayed as li. One thing I am struggling to figure out is how to style the name Joeyc with text-decoration: line-through; on all instances of .book w ...

I've noticed that every time I use the simple-encryptor npm to encrypt something, the output is always different

Can you assist me in solving this issue? var key = 'real secret keys should be long and random'; // Generating an encryptor: var encryptor = require('simple-encryptor')(key); var encryptedText = encryptor.encrypt('testing') ...

CSS smoothly scrolls upward within a set height restriction

Is there a way to use CSS to ensure that the scroll bar of a fixed-height message box is always at the bottom, displaying the latest entry? Currently, as more messages populate the chat box main section, everything inside remains static. The only way to v ...

The event handler attached to the 'click' event will only be triggered upon the second click

After implementing the script, I noticed a strange behavior. When I click it on load, everything works perfectly. However, when I click it via a dynamically created element, the HTML seems to shift or stretch on the first click before returning to normal. ...

Thickness of Border in Bootstrap Cards

I've been attempting to include a thicker border around the entirety of my Bootstrap 4 card. Despite specifying a thicker border, nothing seems to change. Below is a snippet of the code I'm working with: <div class="container"> <di ...

Issue with DropdownListFor validation using jQuery when the onchange event triggers submission

DropdownListFor @Html.DropDownListFor(x => x.selectedDateFilter, new SelectList(Model.bydatefilter, "id", "dt", Model.selectedDateFilter), "--Select Date--", new { onchange = @"this.f ...

Prestashop 1.7 - Enhanced top menu navigation with drop-down subcategories

While using the ps_mainmenu top menu with the default Prestashop theme, I noticed that the drop-down menu only works for parent categories and not subcategories. You can see this in the attached image and HTML code from Chrome. I'm looking for a way t ...

Setting line height as a pixel value does not yield the desired result

$(element).css(options.css).attr(options.attr).addClass(options.class) //ensure line-height is correctly assigned if($(element).is('p') && _.isString(options.css['line-height'])){ console.log('line-height assigned: &apos ...

"Encountering issue with componentDidMount() not functioning as expected, despite debugger being

Hello everyone! This is my first time sharing something here, so I'm eager to hear your feedback on both how I've posted and the content itself. I've only been programming for 8 weeks now, so I'm sure there are plenty of mistakes in wha ...

Removing a specific item from a Kendo UI dropdown list

Recently, I encountered a predicament with a dropdownlist populated from a datasource. Following a certain event, my goal is to eliminate a single item from the dropdownlist identified by id = 22. Although I recognize this may not be the best practice du ...

Trigger Javascript on 'Nearby' input from Html form

I have a JavaScript code that retrieves the latitude and longitude of users from their device for a local search. Although everything works correctly, I want to make sure the script is only executed if the user specifically selects "nearby" as the locatio ...

Passing an ID in Next.js without showing it in the URL

I am looking to transfer the product id from the category page to the product page without showing it in the URL Category.js <h2> <Link href={{ pathname: `/product/car/${title}`, query: { id: Item.id, }, }} as={`/p ...

angularjs issue with $setPrestine function not providing reliable results

I have encountered an issue with the login form code. Initially, I am able to reset the form fields and error messages successfully on the first attempt (both success and failure scenarios work). However, on the second try, I am unable to reset the form fi ...