skip to Main Content

I am trying to run the following code but I KEEP GETTING THE ERROR. I also tried adding document.addEventListener(‘DOMContentLoaded’, (event) => but it is still not working. It dosn’t give me error if I put the code inside console. It also doesn’t give me error when I load it for the first time. But as soon as I refresh it starts giving me errors.

import './Slider.css';
import Acc from './Accomodation/Acc'
import Flora from './Flora/Flora'
import Food from './OurFood/Food.js'
import Trek from './Treks/Treks';
import View from './OurView/View';
import Indoor from './IndoorGames/games';
let slideIndex = 0;
SlideShow()

function SlideShow(){
    
  let slides = document.getElementsByClassName("slide")
  console.log(slides)
  for (let i = 0; i < slides.length; i++) {
      slides[i].style.display = "none"; 
  }
  slideIndex++;
  console.log(slideIndex)
  console.log(slides)
  if (slideIndex === 0) {slideIndex = 1}
  else if (slideIndex === slides.length) {slideIndex = 1} 
  else if (slideIndex > slides.length) {slideIndex = 1} 
  console.log(slides[slideIndex])
  slides[slideIndex-1].style.display = "block"; 

  setTimeout(SlideShow, 10000);

}

function Slider() {


    return (
    <div className='Slider'>
        <h1>Experiences</h1>
        <hr />
        <div className='MySlides'>
        <div className='1 slide fade'>
        <Acc></Acc>
        </div>
        <div className='2 slide fade'>
        <Flora></Flora>
        </div>
        <div className='3 slide fade'>
        <Food></Food>
        </div>
        <div className='4 slide fade'>
        <Trek></Trek>
        </div>
        <div className='5 slide fade'>
        <View></View>
        </div>
        <div className='6 slide fade'>
        <Indoor></Indoor>
        </div>
        </div>
        
        </div>
    
    )  

    
}

export default Slider;

2

Answers


  1. You can use

    try {} 
    catch (error) {console.log(error)}
    

    It will log the error

    And the main problem is slides[slideIndex-1] does not have values so that it can not read styles property

    Login or Signup to reply.
  2. Error message:

    Uncaught TypeError: Cannot read property 'style' of undefined
    

    According to the error message, your code is trying to call the style property; but a specific object doesn’t have the style property. What do I mean by a specific object? An example:

    const someObject = { // the object
     style: 'some value' // the property
    }
    

    So, we need to look at the references of style in your code, and locate the specific parent objects in your code:

    1. slides[i].style.display = "none"; -> the parent object is slides[i]
    2. slides[slideIndex-1].style.display = "block"; -> the parent object is slides[slideIndex-1]

    So, slides[i] or slides[slideIndex-1] objects don’t have the style property.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search