The JavaScript slideshow is malfunctioning by only displaying the initial image and not responding to button clicks

Admittedly, my knowledge of JS is basic. I've taken a few online courses and am now trying to reverse engineer code for projects by changing things around.

I came across a JS slideshow on CodePen and made some modifications. However, the slideshow now only displays the first image without cycling, and the navigation buttons are no longer functional.

You can see what I changed in this fiddle

The JavaScript code snippet looks like this (I added another snippet in the document in case that causes any issues, as it's not included in the fiddle):

$(document).ready(function() {

/*JQuery for fade highlighting of links*/
$(".link").hover(function() {
    $(this).animate({ color:'#fe57a1'}, 100);
}, function() {
    $(this).animate({ color: '#fff'}, 300);
});


/*Slideshow script*/
var on = true;
var myVar = setInterval(function(){ 
    if(on) {slides()}on=true;},3000);

function slides(i) {
    document.getElementsByClassName(".slideImage")[1].style.width="0px";
    document.getElementsByClassName(".slideImage")[2].style.width="100%";
    var slide = document.getElementsByClassName(".slideImage")[0];
    document.getElementById("slide").appendChild(slide);
    if(i) {
        on = false; 
    }
}

function back_slide(i) {
    document.getElementsByClassName(".slideImage")[1].style.width="0px";
    document.getElementsByClassName(".slideImage")[0].style.width="100%";
    var slide = document.getElementsByClassName(".slideImage")[4];
    var slide2 = document.getElementsByClassName(".slideImage")[0];
    document.getElementById("slide").insertBefore(slide,slide2);
    if(i) {
        on = false; 
    }
}
});

The HTML and CSS can be found in the fiddle - I wasn't sure if I should include them here in the post.

Answer №1

Make it a habit to always check the console for errors while debugging. Typically, you can find it in the devtools (F12 on chrome and IE)

Firstly, when using getElementsByClassName, remember that it only takes the class name and not a selector. Therefore, instead of .slideImage, use slideImage when passing it.

document.getElementsByClassName("slideImage")[1].style.width="0px";

Secondly, your slides and back_slide functions (in the fiddle at least) are declared within an onload event (the default option for jsfiddle), so they are not in global scope for the inline js to access.

To resolve this, either change the jsfiddle setting or remove the inline js and utilize addEventListener to attach events to your buttons.

HTML

<button id="prevBtn" class="prev">&#171;</button>
<button id="nextBtn" class="next">&#187;</button>

JS

document.getElementById("prevBtn").addEventListener("click",function(){
   back_slide(true); 
});
document.getElementById("nextBtn").addEventListener("click",function(){
   slides(true); 
});

The final issue you need to address is that you have

var slide = document.getElementsByClassName("slideImage")[4];

The array index should be 3 since array indexes start at 0.

Check out the JSFiddle Demo here

Answer №2

Perhaps your issue lies in the way you are selecting elements. Try using

document.getElementById("slide").getElementsByTagName("div")[1]...
, and you should see some progress.

let isActive = true;
    let timer = setInterval(function(){ 
        if(isActive) {changeSlide()}isActive=true;},3000);
    function changeSlide(i) {
        document.getElementById("slide").getElementsByTagName("div")[1].style.width="0px";
        document.getElementById("slide").getElementsByTagName("div")[2].style.width="100%";
        let slide = document.getElementById("slide").getElementsByTagName("div")[0];
 document.getElementById("slide").appendChild(slide);
        if(i) {
            isActive = false; 
        }
    }
    function previousSlide(i) {
        document.getElementById("slide").getElementsByTagName("div")[1].style.width="0px";
        document.getElementById("slide").getElementsByTagName("div")[0].style.width="100%";
        let slide = document.getElementById("slide").getElementsByTagName("div")[4];
        let prevSlide = document.getElementById("slide").getElementsByTagName("div")[0];
 document.getElementById("slide").insertBefore(slide,prevSlide);
        if(i) {
            isActive = false; 
        }
    }

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 saving an image that has been dragged onto the browser locally

I recently started working with Angular and decided to use the angular-file-upload project from GitHub here. I'm currently in the process of setting up the backend for my application, but I'd like to be able to display dropped files locally in th ...

Generate a dynamic URL using the primary key in Django framework

I've been working on a website where each article has a unique URL generated using a manually entered slug by the admin. However, I want to change it to dynamically generate URLs using pk instead of the slug. Since there is no content uploaded yet, th ...

JQuery Datatable - Customizing column sorting with dynamic number and order of columns

I am currently setting the column attributes for a datatable in a JSP file using the following code snippet. "aoColumns": [ { "bSortable": false, "bSearchable": false, "sWidth": "90px" }, ...

Steps to include a delete option on individual rows in jQuery datatables

Currently, I am working on implementing a jQuery DataTable with AJAX sourced data for my project. The HTML structure of my table is as follows: <table id="dynaFormVersionTable" class="table table-striped table-hover dt-responsive" cellspacing="0" widt ...

What is the best way to connect a relative CSS stylesheet to a master page?

My Java application generates several HTML pages, organized in different directories: html_pages/ | ----> landin_page.html html_pages/details | ----> index1.html html_pages/more_details | ----> index2.html html_pages/css | ...

Cannot access JS variable within Ionic framework

I'm attempting to use a basic JavaScript function to manipulate a div, but I keep encountering an error related to the variable being used: originalText is not defined main.js code: declare var orginalText: any; imports ... export class HomePag ...

Mongoose: utilize populate for fetching records; if not, return an array of records

Learning MeanJS and encountering Mongoose issues. Two models are in question: CategorySchema: - name: String, default:'', required: 'Please fill Category name', trim: true - slug: String, default:'', trim: true, unique: tr ...

Implementing a keypress function that can handle duplicate names

HTML <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="total" type="text" value="0" disabled="disabled"/> Javascript $('[name="pm"]' ...

JavaScript JQuery alert popup fails to display

I have been attempting to create an alert pop-up using JQuery that will display when a user clicks on submit without filling out the form. However, when I test my code by leaving the form empty and clicking 'submit', the page just refreshes with ...

Unable to render properly after saving to Firebase

Currently, I am working on developing an express app that creates a Google map using geo coordinates extracted from photos. My goal is to utilize Firebase for storing data related to the images. While my code is functioning properly, I encountered an issue ...

Enhance User Experience with a Responsive Website Dropdown Menu

Currently, I am focused on enhancing the responsiveness of my website and I realized that having a well-designed menu for mobile view is essential. To address this need, I added a button that only appears when the screen size is 480px or lower, which seems ...

Looking for assistance with aligning the "tape" image on top of another image

I'm attempting to overlay one image on top of another, in order to create the effect of a scrapbook with the images appearing as if they are "taped" onto the homepage. I want to maintain consistency with the tape layer while also allowing myself the ...

The JQuery data table index is displaying as Not a Number

My goal is to retrieve the id and index for a button action, however, the index value is showing as NaN. Below is the console output I am receiving: https://i.sstatic.net/cZ4H8.png ...

Incorporating <span> elements into a comma-separated list using Jquery on every other item

When I receive a comma-separated list of items from a database and insert them into a table cell, I want to apply alternating styles to make it easier for users to distinguish between them. For example: foo, bar, mon, key, base, ball I'm looking to ...

Accessing disks directly with Node.js

I am looking to develop a Node.js module that allows for direct disk access on Windows. This module should have the capability to read, write, and search physical drives or virtual devices. Due to the fact that the built-in fs module relies on native code ...

When using three.js orbitControl, inputting text into textboxes in a Ruby on Rails application is

My three.js application seems to be causing issues with my text field in my Ruby on Rails application. I am unable to write anything in the text field or even click on it. Does anyone know why this is happening? Here is a snippet of my three.js application ...

What is the best way to show a locally stored image in a React application while using a local server?

I have come across a few discussions regarding the display of images in react, but none of them seem to address my specific issue. To start, I initiated a project using npx create-react-app, and then utilized the npm start feature that was included in the ...

Accessing the router URL directly is proving to be ineffective

Currently, I am utilizing react-router in my project and everything is functioning perfectly except for when I directly access the URL. Specifically, if I click on a Link within the application that navigates to "/quizreview?quizId=nAUl3DmFlX", it works fl ...

What is the reason that the CSS property overflow:hidden does not function properly on a table data cell

Why isn't the overflow: hidden property working on my table? <table width="100%" style="table-layout:fixed"> <tr height="200"> <td width="100%" height="200" valign="middle" style="text-align: center; overflow: hidden;"> ...

PhpStorm's error detection for JavaScript syntax does not work in .php files

Currently utilizing PhpStorm 10.0.3 and encountering an issue with JavaScript syntax error detection in the test.php file. It seems that if there are any errors in the JavaScript code, they are not being displayed. For instance: image.setAttribute("data ...