The JavaScript code functions perfectly when inputted directly into the Chrome Developer Console and executed, however, encounters an error when run from the index.html file using the src tag

I am starting from scratch with web development. On my page, there is an image carousel with two buttons for navigating between different images. When I use Brackets live preview to test my website, I encounter the following error message.

Uncaught TypeError: Cannot read properties of undefined (reading 'style') at showSlide (script.js:15:28) at script.js:24:5

Below is the code snippet:

var slideIndex = 0;
var slides = document.getElementsByClassName("mySlides");

    // Function to display the current slide
    function showSlide(n) {
        // Wrap around to the first slide if exceeding the number of slides
        slideIndex = (n + slides.length) % slides.length;

        // Hide all slides
        for (var i = 0; i < slides.length; i++) {
            slides[i].style.display = "none";
        }

        // Display the current slide
        slides[slideIndex].style.display = "block";
    }

    // Function to navigate to the previous or next slide
    function plusSlides(n) {
        showSlide(slideIndex + n);
    }

    // Display the first slide
    showSlide(slideIndex);

The images are not appearing on the screen due to a JavaScript malfunction.

Answer №1

I encountered the same issue when slides.length was 0.

It's possible that

var slides = document.getElementsByClassName("mySlides");
is failing to retrieve the elements in Brackets?

If that's the case:

  • slideIndex = (n + slides.length) % slides.length;
    would result in 0%0, which is NaN
  • for (var i = 0; i < slides.length; i++)
    wouldn't execute the code inside the curly braces
  • slides[slideIndex] would be slides[NaN], translating to undefined. As a result, it lacks a style property, leading to the error

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

Tips for incorporating jQuery val() into a span element!

I am currently working on a plugin that involves interacting with select elements grouped within a span. I want to enhance the functionality of my plugin by adding support for the val() function, which will allow users to easily get or set the 'value& ...

Combine the values of two fields in real-time on a Model-View-Controller Edit form

One challenge I am facing is within an MVC Edit form that contains two fields named ExVAT and VAT. I would like to introduce a new field that displays the total of these two values. Currently, the total only reflects the sum of the two fields upon initial ...

Is it normal for Node's console to not display all object properties?

After running some code, I noticed something peculiar. console.log(myURL); It seems that the extension property is missing: console.log(myURL.extension); However, when logging it on its own, the value appears correctly. The URL object was created ...

Exploring the semantic-ui dropdown menu feature in Chrome

When I first started learning to code with semantic-ui framework, I noticed a difference in behavior in Chrome compared to other browsers. The pointing menu on the left element (such as the search box) breaks down in Chrome, whereas it displays correctly i ...

Trouble confirming the password field with regular expressions in angular.js

I'm trying to validate my password field with specific special characters requirements. The field must contain at least one number, upper case letter, lower case letter, and an underscore, all of which are mandatory. I have attempted to achieve this u ...

"Encountering issue with undefined request body in Node Express on AWS Lambda

My current project involves using AWS Amplify to create Node Express REST API endpoints. I recently implemented a new endpoint, but I am encountering an issue where the request body is showing as undefined. I have been unable to pinpoint where I may have ...

Adding a div via an Ajax call is only successful during the initial page load

Currently, I am utilizing a combination of YQL and jQuery to retrieve content from a distant page. While I am able to successfully load the content during the initial page load, I encounter an issue when attempting to return to the same page after navigati ...

Unable to display the column data labels in Highcharts due to the incorrect formatting being presented

I'm having trouble displaying the datetime format at the top of a column in my chart. Although the tooltip shows the correct data when hovering over the columns, the labels are not formatted properly. Received output - 86340000 Expected output - 23: ...

Using cannonjs and Three.js to connect a physics body with a visual mesh

I have written the code below to create two spheres using cannonjs with Three.js for rendering. var world, mass, body, shape, timeStep=1/60, camera, scene, renderer, geometry, material, mesh; initThree(); initCannon(); animate(); func ...

Make the table width 100%, but we don't want the central cell to be stretched

My table contains a central image cell that spans two rows: <table width="100%" style="text-align:center"> <tr> <td>Cell 1</td> <td>Cell 2</td> <td rowspan="2"><img src="http://www.skrenta.com/ima ...

Mastering the Art of Defining JavaScript Classes in React-Native

In my React Native project, I am faced with a situation where I need to create a new class: class customClass { email: string; name: string; constructor() { setUser(fbid: string, token: string): boolean { To keep things organized, I decide ...

What are the steps to incorporate an iframe containing uniquely designed XML content?

I'm currently working on a website project for a client who specifically wants to include news from the BBC. Despite spending 3 hours searching online, I haven't been able to successfully insert an XML file into an iframe and style it to the clie ...

The alignment of the HTML and CSS speech bubble is experiencing issues

I need help with CSS as I am new to it and trying to create a speech bubble. However, when the text inside the bubble is long, it overlaps the timestamp. I am currently using `display: inline-block;` in my CSS. Below are snippets of my HTML and CSS code: ...

Displaying WordPress plugin queries in a linked file

I have been working on developing a custom WordPress plugin that involves querying a database based on user input and then displaying the results in an HTML file with links. While I have managed to successfully display the HTML page, I am facing an issue w ...

What's the method for positioning the footer at the bottom of the grid without impacting the layout of the other rows?

I am trying to achieve the placement of the footer at the bottom of the layout page when the height is shorter than the window. While it is often suggested to use min-height:100vh, this approach ends up increasing the height of other elements as well. I am ...

Inaccurate audio timestamps in Chrome

I am currently working on a web application that features an audio component sourced from a local .mp3 file lasting approximately 1 hour. I have encountered an issue where, upon clicking the seekbar to jump to a specific point in the audio (e.g., 00:01:00) ...

Hide an Angular button when a page is loaded, depending on the information found in a table

How can I hide the Submit button in a table row if a certain condition is met based on information from the database? I attempted to create a function that returns true or false, but it ends up crashing my program because it runs continuously. I also trie ...

What is causing this div to automatically assume a width of 900 pixels?

There is only one specific instance where I have set a div width to 900 px, and it is located further up the DOM within a div called #Ba. This is where the width is being derived from. My intention is for it to simply take on the width of its containing e ...

Determine the shared elements between two distinct arrays and create an object that includes these common elements

I am dealing with 2 different arrays of objects var array1 = [ {id: 1, name:'fruit', rating:5}, {id: 4, name:'vegetable', rating: 3}, {id: 8, name:'meat', rating:1} ]; var array2 = [ {alimentId: 1, quantity: 2}, {alimentId: 4 ...

The oncanplaythrough event is not functioning properly in Internet Explorer

I am facing an issue where the beep sound trigger upon receiving an API response works perfectly in Chrome and Firefox browsers, but unfortunately, it does not work in Internet Explorer. if ($scope.totalQueueList) { var audio = new Audio(); audio.s ...