Showing a variety of pictures within a specified time frame

In my CSS, I have defined classes that allow me to display different background images on a page at set intervals:

.image-fader {
 width: 300px;
 height: 300px;
}

.image-fader img {
 position: absolute;
 top: 0px;
 left: 0px;
 animation-name: imagefade;
 animation-timing-function: ease-in-out;
 animation-iteration-count: infinite;
 animation-duration: 8s;
}

@keyframes imagefade {
0% {
opacity: 1;
 }
 17% {
 opacity: 1;
 }
 25% {
 opacity: 0;
 }
 92% {
 opacity: 0;
 }
 100% {
 opacity: 1;
 }
}

.image-fader img:nth-of-type(1) {
animation-delay: 6s;
}
.image-fader img:nth-of-type(2) {
animation-delay: 4s;
}
.image-fader img:nth-of-type(3) {
animation-delay: 2s;
}
.image-fader img:nth-of-type(4) {
animation-delay: 0;
}

Currently, I only have CSS code for a single default image:

.defaultHero,
.roomsHero {
min-height: calc(100vh - 66px);
background: url("./images/defaultBcg.jpeg") center/cover no-repeat;
display: flex;
align-items: center;
justify-content: center;
}

The structure of my Hero Component is as follows:

import React from 'react'

export default function Hero({children, hero}) {
return (
<header className={hero}>
    {children}
</header>
)
}

Hero.defaultProps = {
hero: "defaultHero"
};

I am using the Hero Component in my Homepage like this:

import React from 'react'
import Hero from "../Components/Hero";
import Banner from "../Components/Banner";
import {Link} from 'react-router-dom';


export default function Home() {
return (
    <Hero>
        <Banner title="Affordable Apartments" subtitle="Family
    Apartments Starting At &#8364;90 per night">
    <Link to= "/rooms" className="btn-primary">
        our apartments
    </Link>
    </Banner>
    </Hero>
  );
 }

}

How can I incorporate the image-fader class into my Home page to display multiple background images sequentially? Is there a better way to achieve this functionality without relying on the image-fader class?

Answer №1

To create your HTML code, follow these steps:

<!DOCTYPE html>
<html>
    <div class="c1" id="slideShowImages">
        <img src="Image/1.jpg">
        <img src="Image/2.jpg">
        <img src="Image/3.jpg">
    </div>
    <script src="slideShow.js"></script>
</html>

After that, make a file named slideShow.js and insert the following code:

window.addEventListener('load', slideShow, false);

function slideShow() {

  /* GLOBALS **********************************************************************************************/

  var globals = {
    slideDelay: 6000, 
    fadeDelay: 55, 
    wrapperID: "slideShowImages",
    buttonID: "slideShowButton", 
    buttonStartText: "Start Slides", 
    buttonStopText: "Stop Slides",    
    wrapperObject: null, 
    buttonObject: null, 
    slideImages: [], 
    slideShowID: null, 
    slideShowRunning: true,     
    slideIndex: 0 
  }

  /* MAIN *************************************************************************************************/

  initializeGlobals();  

  if ( insufficientSlideShowMarkup() ) {
    return; 
  }

   // Assert: there's at least one slide image.

  if (globals.slideImages.length == 1) {
    return; 
  }

  // Assert: there's at least two slide images.

  initializeSlideShowMarkup();

  globals.wrapperObject.addEventListener('click', toggleSlideShow, false); 

  if (globals.buttonObject) {
    globals.buttonObject.addEventListener('click', toggleSlideShow, false); 
  } 

  startSlideShow();

  /* FUNCTIONS ********************************************************************************************/

  function initializeGlobals() {   
    globals.wrapperObject = (document.getElementById(globals.wrapperID) ? document.getElementById(globals.wrapperID) : null);
    globals.buttonObject = (document.getElementById(globals.buttonID) ? document.getElementById(globals.buttonID) : null);   

    if (globals.wrapperObject) {
      globals.slideImages = (globals.wrapperObject.querySelectorAll('img') ? globals.wrapperObject.querySelectorAll('img') : []);
    }
  } // initializeGlobals

  function insufficientSlideShowMarkup() {
    if (!globals.wrapperObject) { 
      if (globals.buttonObject) {
        globals.buttonObject.style.display = "none"; 
      }
      return true;
    }

    if (!globals.slideImages.length) { 
      if (globals.wrapperObject) {
        globals.wrapperObject.style.display = "none"; 
      }

      if (globals.buttonObject) {
        globals.buttonObject.style.display = "none";         
      }

      return true; 
    }

    return false; 
  } // insufficientSlideShowMarkup

  function initializeSlideShowMarkup() {  
    var slideWidthMax = maxSlideWidth(); 
    var slideHeightMax = maxSlideHeight(); 

    globals.wrapperObject.style.position = "relative";
    globals.wrapperObject.style.overflow = "hidden"; 
    globals.wrapperObject.style.width = slideWidthMax + "px";
    globals.wrapperObject.style.height = slideHeightMax + "px";

    var slideCount = globals.slideImages.length;
    for (var i = 0; i < slideCount; i++) { 
      globals.slideImages[i].style.opacity = 0;
      globals.slideImages[i].style.position = "absolute";
      globals.slideImages[i].style.top = (slideHeightMax - globals.slideImages[i].getBoundingClientRect().height) / 2 + "px";   
      globals.slideImages[i].style.left = (slideWidthMax - globals.slideImages[i].getBoundingClientRect().width) / 2 + "px";               
    }

    globals.slideImages[0].style.opacity = 1; 

    if (globals.buttonObject) {
      globals.buttonObject.textContent = globals.buttonStopText;
    }
  } 

  function maxSlideWidth() {
    var maxWidth = 0;
    var maxSlideIndex = 0;
    var slideCount = globals.slideImages.length;

    for (var i = 0; i < slideCount; i++) {
      if (globals.slideImages[i].width > maxWidth) {
        maxWidth = globals.slideImages[i].width; 
        maxSlideIndex = i; 
      }
    }

    return globals.slideImages[maxSlideIndex].getBoundingClientRect().width; 
  } 

  function maxSlideHeight() {
    var maxHeight = 0;
    var maxSlideIndex = 0;    
    var slideCount = globals.slideImages.length;

    for (var i = 0; i < slideCount; i++) {
      if (globals.slideImages[i].height > maxHeight) {
        maxHeight = globals.slideImages[i].height; 
        maxSlideIndex = i; 
      }
    }

    return globals.slideImages[maxSlideIndex].getBoundingClientRect().height; 
  } 

  function startSlideShow() {
    globals.slideShowID = setInterval(transitionSlides, globals.slideDelay);                
  } 

  function haltSlideShow() {
    clearInterval(globals.slideShowID);   
  } 

  function toggleSlideShow() {
    if (globals.slideShowRunning) {
      haltSlideShow();
      if (globals.buttonObject) { 
        globals.buttonObject.textContent = globals.buttonStartText; 
      }
    }
    else {
      startSlideShow();
      if (globals.buttonObject) { 
        globals.buttonObject.textContent = globals.buttonStopText; 
      }            
    }
    globals.slideShowRunning = !(globals.slideShowRunning);
  } 

  function transitionSlides() {
    var currentSlide = globals.slideImages[globals.slideIndex];

    ++(globals.slideIndex);
    if (globals.slideIndex >= globals.slideImages.length) {
      globals.slideIndex = 0;
    }

    var nextSlide = globals.slideImages[globals.slideIndex];

    var currentSlideOpacity = 1; 
    var nextSlideOpacity = 0; 
    var opacityLevelIncrement = 1 / globals.fadeDelay;
    var fadeActiveSlidesID = setInterval(fadeActiveSlides, globals.fadeDelay);

    function fadeActiveSlides() {
      currentSlideOpacity -= opacityLevelIncrement;
      nextSlideOpacity += opacityLevelIncrement;

      if (currentSlideOpacity >= 0 && nextSlideOpacity <= 1) {
        currentSlide.style.opacity = currentSlideOpacity;
        nextSlide.style.opacity = nextSlideOpacity; 
      }
      else {
        currentSlide.style.opacity = 0;
        nextSlide.style.opacity = 1; 
        clearInterval(fadeActiveSlidesID);
      }        
    } 
  } 

} 

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

Reactjs Rendering problem with retrieving data from the backend in a popover

Take a look at the test environment where this problem is occurring https://codesandbox.io/s/nice-cache-kl12v My website design is being done with antd. Right now, I'm facing an issue where I need to display notifications to the user, which are acces ...

Issue with npm installation leading to missing node_modules directory

When attempting to run npm install . in a local directory, I keep encountering the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 15.2.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "." npm ERR! no ...

Using the IE method getelementbyid to target an object within the document

Is there a way to use getElementById to access an object that already exists in the document? I am specifically trying to target the element "test" which is nested within parentDiv1. While this code works in Firefox, it's not functioning properly ...

Alter the appearance of the mouse cursor when hovering over input fields in HTML

I am working with a variety of HTML elements that can be moved via Drag'n'Drop. In order to indicate to the user where these elements can be dropped, I change the cursor's appearance using CSS classes applied through JavaScript. This method ...

Counting JQuery Classes in an HTML Document

My task involves creating a dynamic HTML form that allows users to enter card values, which are then counted and styled accordingly. Each set of cards is contained within a <section> element. However, I encountered an issue with my jQuery code where ...

Sending an object over to a different page

Need some assistance with displaying JSON data that is being repeated using ng-repeat. { "title": "image title", "description": "Lorem ipsum dolor sit amet, per ea ferri platonem voluptaria, ea eum ubique ornatus interpretaris. Dolore erroribus reprimique ...

Skipping is a common issue encountered when utilizing Bootstrap's Affix feature

I'm trying to implement Bootstraps Affix feature in a sticky subnav. <div class="container" data-spy="affix" data-offset-top="417" id="subnav"> I've adjusted the offset to ensure there's no "skip" or "jump" when the subnav sticks. Ho ...

The signOut() function of firebase.auth() is failing to redirect back to the mainNav after logging out

While developing my react native app with Firebase integration, I encountered a minor issue when attempting to log out a user. Currently, upon pressing the logout button, the app fails to redirect back to the login page. Home <Text>Home Screen</T ...

Struggling to grasp the concept of PHP LZW decompression function within JSend framework

I am currently working on converting the LZW decompressor from PHP to JavaScript and I have encountered a function that is giving me some trouble. function decompressLZW(aCodes) { var sData = ''; var oDictionary = []; for (var i = 0; i &l ...

How can I use a button to save all changes made in a JqGrid checkbox column simultaneously?

In my jqgrid, there is a column named 'asistencia' which displays data from a database as checkboxes. These checkboxes are pre-checked based on the property formatoptions: {disabled : false}. I would like to implement a 'save' button th ...

If the span id includes PHP data that contains a certain phrase

Hey there, it's my first time posting and I'm in a bit of a bind with this script... Let me give you some background information first I am trying to create a click function for a register button that will check the span id (e.g. $("#username_r ...

Using CSS to show only the central portion of an image

How can I display only the center part of an image with dimensions height=300px and width=520px using CSS or jQuery? I tried searching on Google, but didn't find a solution. Is it possible to show only a 200x130 section from the center of an image us ...

Array Filtering with Redux

I have come across similar queries, but I am still unable to find a solution. While typing in the search box, the items on the screen get filtered accordingly. However, when I delete a character from the search box, it does not show the previous items. For ...

Link tag does not activate the onSubmit function when the submit button in the form is clicked

Whenever I put my Link tag around my form's submit button, the onSubmit() function doesn't seem to be triggered. Can someone help me figure out what mistake I am making? import { Link } from "react-router-dom"; <form className= ...

Dealing with unanticipated consequences in computed attributes - Vue.js

I am facing a challenge while working on the code below. I am attempting to utilize the getTranslation object to match values from the originalKeys array and then add these values to a new array called allKeys. However, ESLint has flagged an error stating ...

Encountering an error message that reads "State.Push is not a valid function" upon integrating

Currently, I am working on developing a Todo app using react-typescript and redux. During testing, I noticed that the app functions properly without redux-persist, displaying the list of added tasks. However, upon integrating redux-persist, the store does ...

Updating JSON data using fetch API

Hi everyone, I'm currently working on an email application and need help with implementing an archive button for each email. It seems that the function to change the archived status to true is being called, but for some reason, it's not making th ...

How can I make a basic alert box close after the initial click?

After clicking a button, I have a simple jQuery script that triggers a fancybox. However, the issue is that the fancy box does not close after the first click of the button; it only closes after the second click... Another problem arises inside the fancy ...

Nodejs: A function is expected in the instanceof check, but an undefined value was provided

Encountering a peculiar error while using node-webkit, here's a detailed example to replicate it: index.js: var jQuery = require('jquery'); var Backbone = require('backbone'); (function($){ var ListView = Backbone.View.extend( ...

Issue with Selenium: Unable to select the WebElement

I am a beginner with selenium and I have encountered a problem while trying to click on a specific element using the following locators. Unfortunately, none of them seem to work as expected and my scripts just skip over that particular line without any err ...