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

Whoops! Unable to interpret properties from an undefined source while trying to retrieve 'get'

Every time I execute my program, I encounter the following error: Cannot read properties of undefined (reading 'get') TypeError: Cannot read properties of undefined (reading 'get') at Proxy.mounted (webpack-internal:///./node_module ...

Exploring the concept of JavaScript closures and the pitfalls of name clobber

Is it possible for variables defined inside an inner function with the same name as a variable in an outer function to be isolated from the outer variable? function() { var myTest = "hi there"; ( function( myLocalTest ) { myLocalTest = "go ...

The markers within a loop in react-native-maps are failing to render

Recently, I've been delving into the world of React Native app development for iOS. Specifically, I've been experimenting with the react-native-maps package. Here's the issue I'm facing: When I statically render a single MapView.Marker, ...

I require assistance on how to properly arrange images in a div so that they stack

I'm having an issue with arranging a series of images within a div where they stack on top of each other. The div has a CSS width of 450px, and the top image always matches this width. Subsequent images vary in size and need to be aligned flush right ...

Express and Angular2 Webpack integration

Recently, I set up Angular 2 with Webpack and explored its routing capabilities through a sample app. I am now interested in integrating Angular2 for front end routing while utilizing ExpressJS for a RESTful API backend on the same server. For example, ht ...

looping through the elements in a collection using a for-in loop

Issue with IE 11 Console Chrome Console Behavior When changing the word 'item' to 'anotherItem' in the loop like so: var obj = { id1: 'item 1', id2: 'item 2', id3: 'item 3' }; for (anothe ...

Is it feasible to transition a mobile webpage seamlessly without using jqm?

I'm currently developing a Phonegap app and I am trying to steer clear of jqm in my project. I find that the css is causing some issues with the html code. As a workaround, I can transition between pages using: window.location = "profiles.html"; How ...

The error message "dispatch is undefined - mapDispatchToProps is not being passed through the Router" indicates a problem with how the

I am encountering an dispatch is not defined issue with the 'shopfront' code. My assumption is that I might not be passing down the properties to the next level correctly, but I'm uncertain about it. My objective is to ensure that the di ...

Perform an update followed by a removal操作

I've been facing a persistent issue that has been troubling me for quite some time now. The setup involves a database in MariaDB (using WAMP) and an API in ExpressJS. Within the database, there are two tables: "menu" and "item," with a foreign key rel ...

Transitioning from a fixed position to absolute in CSS3

Sticky Logo Element In my project, I implemented a logo element that is positioned absolutely within the document. As the user scrolls, the logo sticks to the top of the window with a fixed position (you can view an example here: https://jsfiddle.net/swzb ...

Transfer the selected user content from one canvas to another

After successfully implementing a simple selection area on canvasA, I encountered an issue with copying the area to canvasB. The user is supposed to select an area and then see that selection appear on another canvas once they finish making the selection b ...

Having trouble creating an axios instance in Vue

I recently came across a helpful tip in an article about using axios for AJAX requests in Vue. The author mentioned that by setting Vue.prototype.$http = axios, we can then use this.$http within the Vue instance, which worked perfectly for me. However, wh ...

Guide to encapsulating the render Function in React

I have already wrapped the render function in ES5 like: var Test = React.createClass({ componentDidUpdate:function() { this.refs.table.cleanSelected(); }, getInitialState: function() { return getItemPropertyData(); }, ...

Error message indicating that externally displayed Json Data is not being passed to ReactJS components: "embedded:44 Uncaught TypeError: Cannot read property 'state' of undefined."

My mind is on fire. After hours of work, I'm facing a persistent error when trying to pass externally retrieved json data to ReactJS components. Below is the error message that's giving me a headache: embedded:44 Uncaught TypeError: Cannot read p ...

In the latest version of NextJS 13, the styled-components CSS is not being properly

In my current project, I am utilizing NextJs version 13.4.10 and styled-components version 6.0.4. Interestingly, when I initially run the project (npm run dev), all styles are successfully applied. However, if I make a code change and re-render the project ...

Concealing a hyperlink within a DIV by removing or hiding it

I am looking to temporarily hide or remove a specific link (team.aspx) within a drop-down menu, with the intention of adding it back in later. Here is my current code: <div id="nav_menu"> <ul id="nav"> <li class="current"><a href= ...

Playing with Data in AG-Grid using Javascript

I am working on implementing data display using AG Grid with an AJAX call, but I am facing an issue where no data is being shown in the grid. Even though my AJAX call seems to be functioning correctly and returning the desired object List, the grid itsel ...

Modifying HTML code within a WebView (Monodroid) explained

WebView webView = FindViewById<WebView>(Resource.Id.webView1); webView.HorizontalScrollBarEnabled = false; webView.LoadUrl("res.htm"); I am looking for a way to modify certain parts of HTML code in my file and display it using webView without actual ...

Requesting a resource using the HTTP GET method returned no data

Looking to process the response from an http-request using JavaScript? Check out this straightforward example below. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html x ...

Transforming a unirest 'GET' call into an axios request

I am currently utilizing TheRundown API to access sports data. The example provided to me makes use of unirest, but I am endeavoring to adapt that example into an axios request. While I have managed to make it work for the most part, my main challenge lies ...