1

I decided to create small, simple slider with the help of Sitepoint tutorial as a part of my practice.

Unfortunately, as the code works in their tutorial, it does return an error for me saying:

TypeError: Cannot set property 'className' of undefined at nextSlide

When I set everything up in the jsfiddle ( here is the link https://jsfiddle.net/9ndfhn4e/ ) everything works just fine.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Gulp Starter Environment</title>
  <link rel="stylesheet" href="css/main.css"/>
  <script src="js/j.js"></script>
</head>
<body>
  <ul id="slides">
      <li class="slide showing">Slide 1</li>
      <li class="slide">Slide 2</li>
      <li class="slide">Slide 3</li>
      <li class="slide">Slide 4</li>
      <li class="slide">Slide 5</li>
  </ul>
</body>
</html>

CSS

* {
  box-sizing: border-box; }

html, body {
  width: 100%;
  height: 100%; }

.main {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex; }

#slides {
  position: relative;
  height: 300px;
  padding: 0px;
  margin: 0px;
  list-style-type: none; }

.slide {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  opacity: 0;
  z-index: 1;
  transition: opacity 1s; }

.showing {
  opacity: 1;
  z-index: 2; }

.slide {
  font-size: 40px;
  padding: 40px;
  box-sizing: border-box;
  background: #333;
  color: #fff; }

.slide:nth-of-type(1) {
  background: red; }

.slide:nth-of-type(2) {
  background: orange; }

.slide:nth-of-type(3) {
  background: green; }

.slide:nth-of-type(4) {
  background: blue; }

.slide:nth-of-type(5) {
  background: purple; }

JS

var slides = document.querySelectorAll("#slides .slide");
var currentSlide = 0;
var slideInterval = setInterval(nextSlide,2000);

function nextSlide() {
    slides[currentSlide].className = "slide";
    currentSlide = (currentSlide+1)%slides.length;
    slides[currentSlide].className = "slide showing";
}

I Believe it might be environment problem, but I cannot think of anything. Maybe someone has an idea. Thanks for help .

nerwusik
  • 61
  • 1
  • 5

1 Answers1

2

When you create a fiddle, the default settings for javscript load type is onLoad. This places your script in the head of the document like so:

<head>
...
    <script>
        window.onload=function(){
            ...your code...
        }
    </script>
...
</head>

What I'm assuming you have done, is placed your code into the body of the document as you have typed it into the JSFiddle javascript editor.

The problem is, the DOM hasn't loaded yet and cannot find your document.querySelectorAll("#slides .slide") because they do not exist.

You either have to attach your code to an onLoad event, or place your code at the bottom of the document to ensure the DOM has loaded before your script executes.

Kramb
  • 984
  • 8
  • 18