Trying to create a simple image slider that pulls information from various sources. CSS and HTML are set up properly, but adding the JavaScript logic causes all images to disappear. The console displays an error saying "Uncaught TypeError: Cannot read property 'style' of undefined," indicating that the array of elements containing the images is empty. However, a console log before the error message shows three images as expected.
Since I am using Web Maker, using "onclick" is not an option. Any suggestions on how to resolve this issue? It seems like a basic problem, but I can't seem to pinpoint it. (see code below)
HTML
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
</style>
</head>
<body>
<div id="myslider">
<img class="slide" src="http://chromethemer.com/wallpapers/chromebook-wallpapers/download/work-space-3840x2160.jpg">
<img class="slide" src="http://lindstrominsuranceagency.com/wp-content/uploads/2015/10/business.jpeg">
<img class="slide" src="http://www.nomisconnections.co.uk/wp-content/uploads/2016/10/image-1377543510.jpg">
<button id="left-button"><i class="fa fa-chevron-left"></i></button>
<button id="right-button"><i class="fa fa-chevron-right"></i></button>
</div>
</body>
</html>
CSS
#myslider {
position: relative;
height: 360px;
width: 700px;
}
.slide {
height: 100%;
width: 100%;
position: absolute;
/* opacity: 0; */
transition: 1s;
}
button {
position: absolute;
z-index: 1;
top: 50%;
background: rgba(0,0,0,0.8);
border: none;
padding: 10px;
color: #fff;
cursor: pointer;
}
button:nth-of-type(2) {
right: 0;
}
JavaScript
document.getElementById("left-button").addEventListener("click", plusDivs(-1));
document.getElementById("right-button").addEventListener("click", plusDivs(1));
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
console.log("inside of plusDiv(n)");
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("slide");
console.log(x);
if (n > x.length) {slideIndex=1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i <x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex - 1].style.display = "block";
}