The novice image slideshow script in JavaScript is causing all images to disappear and generating errors

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";
}

Answer №1

It seems like you've placed your callback functions incorrectly within the addEventListener methods. To pass parameters in a function, you should invoke the function inside an anonymous function.

Here are some ways to handle this:

If you don't need to use function parameters, insert the function-object directly.

function someFunction(){
   // Your code here
}
elem.addEventListener('click', someFunction);

Alternatively, you can use an anonymous function.

elem.addEventListener('click', function(){
   // Your code here
});

To include a parameter in the function, wrap it within an anonymous function.

function someFunction(parameter){
   // Your code here
}
elem.addEventListener('click', function(){
   someFunction(parameter);
});

I would also recommend checking out the MDN docs for further information: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

PS: It's advisable to use more descriptive variable names instead of generic ones like x, n, or i.

Your updated code with corrected addEventListener methods

document.getElementById("left-button").addEventListener("click", () => {plusDivs(-1)});
document.getElementById("right-button").addEventListener("click", () => {plusDivs(1)});

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("slide");
  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";
}
#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;
}
<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>

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

Determine the total quantity of colored cells within a row of an HTML table and display the count in its own

I need assistance with a table that has 32 columns. From columns 1 to 31, I am able to fill in colors by clicking on the cells. However, I now want to calculate and display the number of cells that are not colored in the last column. This task must be co ...

What is the process of transforming an xhr request into an angular $http request?

I've been successfully loading images using ajax with the following code. However, when trying to convert it into Angular and use $http, it's not working as expected. Original ajax code var xhr = new XMLHttpRequest(); xhr.open('GET', ...

Guide to uploading multiple images to an Amazon AWS S3 bucket using Node.js, Angular, and JavaScript

Can anyone share insights on where and how E-commerce websites typically upload their product images? Has anyone had experience using Amazon AWS S3 bucket for this purpose? Additionally, does anyone know how to upload or retrieve multiple images at once ...

Limit the bootstrap datepicker to display only certain dates and today's date

I've integrated the Bootstrap Datepicker into my website. I need to customize it so that only specific dates are enabled, including today's date, and all other years, months, and days are hidden from the Datepicker. How can I achieve this? Furth ...

vuejs props become null upon page refresh

MyComponent.vue template: <ResponsiveNavigation :nav-links="navLinks" /> script data: () => ({ navLinks: [] }), created: function() { this.getSocialMediaLinks(); }, methods: { getSocialMediaLinks() { var self = this; ...

What is the best way to convert a JSON object into a string containing a negative zero in JavaScript?

Is there a way to properly convert a negative zero into a string using JSON.stringify? I've noticed that JSON.stringify often converts negative zero into a positive one, which is not the desired outcome. Any suggestions for an alternative approach? v ...

Enhance User Experience with JQuery Autocomplete for Internet Explorer 8 Using ASMX Web Services

Help Needed! I have been trying to implement a Web Service (ASMX) file on my website. When I access and query the page, I receive the desired results. The problem arises when I attempt to add autocomplete functionality to a textbox in my ASP.NET applicati ...

Displaying Kartik's growling animation using AJAX within Yii2 framework

Utilizing kartik growl to display a message via ajax success I attempted the following: This is the javascript code: $.post({ url: "forwardpr", // your controller action dataType: 'json', data: {keylist: keys,user:userdata}, success: f ...

Having four videos displayed on one webpage can cause the browser to function at a slower

I have videos that are around 30 seconds long and 15mbs. I'm wondering if it's feasible to include them on a page or if I should opt for cover images instead. I would like to use the video as a separator similar to the design showcased at Does a ...

Tips for inserting an icon alongside a list item in HTML

https://i.sstatic.net/sTWRu.png Can you help me with adding an icon to a list item using Font Awesome or any other method? I want the icon to appear on the right side of the text. I have four sections of text that I want to convert into expandable dropdow ...

Selection pseudo selectors for tooltips are a great way to provide additional

Can someone explain how tooltips change on Medium.com when you double click a word or sentence to reveal options like share and edit? https://i.stack.imgur.com/0EVmH.png ...

Some of the picture remains concealed without spilling over

I've been struggling to get my logo to display properly on my website. I have managed to position it, but the image isn't fully visible. Here's a screenshot for reference: http://gyazo.com/1d23c924cdb401fc0cca76b946e57dcb There doesn't ...

Expanding the content of :before

I have implemented the code below to enable a hover effect when users hover over an image: &:before ' content: "example image" Background: #444; Padding: 20px Height: 300px Width: 300px Font family: 'open sans' Opacity: 0; ' &: ...

The array is failing to pass through ajax requests

Here is the JavaScript code snippet for making an AJAX call. In this scenario, the code variable is used to store a C program code and then pass it on to the compiler.php page. function insert(){ var code = document.getElementById("file_cont").val ...

Error: The last line is missing a trailing comma

I'm struggling to understand why my tslint insists on having a trailing comma at the end of the last line in the objects. Is there a way to configure the ignore rule for the last line of objects? Appreciate any help! For example: settings = { ...

Transferring information from child to parent class in TypeScript

I have a scenario where I have two classes (Model). Can I access properties defined in the child class from the parent class? Parent Class: class Model{ constructor() { //I need the table name here. which is defined in child. } publ ...

Embellishing Your Website with Unique Cursor Styles

Looking to add personalized cursors to my website using asp.net 4.0. On my master page, I aim to set a custom cursor as the default for the entire site and have different custom cursors for all links. Is this achievable? ...

D3 - Rounded edge chart width

Currently facing an issue with the chart where the data value is small, resulting in an 'ear' effect. Can anyone help me with this problem? Below is the code I am currently using: const rx = 30; const ry = 30; svg ...

Nuxt - Sending Relative Path as Prop Leads to Error 404

I am currently working with an array of JSON objects that I need to import onto a webpage. The process involves iterating through the data and passing the objects as a prop to a component. One of the attributes within the JSON data is a relative path for a ...

Unable to retrieve data from the database within PHP code

I have successfully built a shopping cart website utilizing SQL, HTML, and PHP. Below is the code snippet for the 'Add to Cart' button: <form method="post" action="cart.php" class="form-inline"> <input type="hidden" value="&apos ...