Attempting to switch between classes with the click of a button

I am attempting to create a basic animation that involves changing an image from A to B to C when a button is clicked. However, I am encountering an issue with the error message

Cannot read properties of undefined (reading 'classList')
. I am puzzled as I have successfully used a similar structure for a carousel in the past without any problems.

My goal is to switch the elements from "seed" to Bootstrap's ".d-none".

var javaButton = document.getElementById("button-trigger");

const track = document.querySelector(".plant-wrapper");
const slides = Array.from(track.children);
const targetIndex = slides.findIndex;
const hidden = document.querySelector(".d-none");
const seeds = document.querySelector(".seed");

javaButton.addEventListener("click", moveToSlide);

function moveToSlide(slides, seeds, hidden, targetIndex) {
if (targetIndex === 0) {
  seeds.classList.add("is-hidden");
  hidden.classList.remove("is-hidden");
} else if (targetIndex === slides.length - 1) {
  seeds.classList.remove("is-hidden");
  hidden.classList.add("is-hidden");
} else {
  seeds.classList.remove("is-hidden");
  hidden.classList.remove("is-hidden");
}
};
<button type="button" id="button-trigger">Explore!</button>
<div class="plant-wrapper">
  <img src="images/seed.png" class="seed mx-auto d-block" id="seed1">
  <img src="images/sprout.png" class="mx-auto d-block d-none" id="seed2">
  <img src="images/stem.png" class="mx-auto d-block d-none" id="seed3">
  <img src="images/pot.png" class="pot mx-auto d-block">
</div>

Answer №1

An issue arises when you fail to provide arguments to the moveToSlide function

This can be resolved by removing arguments from the moveToSlide function (as it will read variables declared above)

function moveToSlide() {
  // Code...
}

Alternatively, you can pass values to the function (which is the recommended option)

javaButton.addEventListener("click", () => moveToSlide(slides, seeds, hidden, targetIndex))

Answer №2

If you're looking to create a slider, there are alternative methods that can be used.

Check out a demo from w3schools on how to create a slider: https://www.w3schools.com/howto/howto_js_slideshow.asp

Here's a different approach to building a slider:

index.html

<button type="button" id="button-trigger" onclick="changeImg()">Click here!</button>

<div class="plant-wrapper" id="plant-wrapper">
</div>

index.js

var index = 0;

const imageArray = [
    "images/1.png",
    "images/2.png",
    "images/3.png",
    "images/4.png"
];

function changeImg(){
    (index == imageArray.length - 1 ? index = 0 : index++);
    showImage();
}

function showImage(){
    document.getElementById("plant-wrapper").innerHTML = '<img src="' + imageArray[index] + '" class="mx-auto" />';
}   

window.onload = function() {
    showImage()
}

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

Issues arise when attempting to transfer strings through ajax to a Node.js server that is utilizing express.js

On my website, I am encountering a problem where certain characters are being lost when I send strings to my Node.js server. // Client: microAjax("/foo?test="+encodeURI("this is ++ a test"), function callback(){}); // Server: app.get('/foo',fun ...

Obtaining various object values from a data set

I need help with identifying elements in an object: object["key1"] = "text1" object["key2"] = "text2" object["key3"] = "text1" object["key4"] = "text3" How can I alert the elements that have the same values (such as text1, text2, etc.)? For the provided ...

Tips on extracting data from an API using jQuery

Struggling with parsing data and feeling a bit stuck. That's why I'm reaching out for assistance. This is where I need help: How do I specifically retrieve market_cap values? Each value needs to be accessed individually for a specific string I ...

Having trouble with the close button functionality on a Toast in Bootstrap?

I just started learning about Bootstrap v5 and I encountered an issue with the close button not working for Toasts in my code. Even though I copied the code directly from the website, the button does not dismiss the toast. Here is a snippet of my code: & ...

What is the best way to name a force-directed Graph using d3?

I'm struggling to label the nodes in my force-directed graph created with d3.js. Despite trying various solutions from StackOverflow and online tutorials, I believe my issues stem from a lack of fundamental understanding of JavaScript. https://i.sstat ...

Alternating row colors using CSS zebra striping after parsing XML with jQuery

After successfully parsing XML data into a table, I encountered an issue with applying zebra stripe styling to the additional rows created through jQuery. Despite my efforts to troubleshoot the problem in my code, I remain perplexed. Below is a snippet of ...

Adjust the color of a selected edge in Three.js

let cubeEdges = new THREE.EdgesHelper(cube, 0xff0000); cubeEdges.material.linewidth = 5; scene.add(cubeEdges); A cube has been created using the following code: new THREE.Mesh(new THREE.BoxGeometry(200, 200, 200, 1, 1, 1, materials), new THREE.MeshFaceMa ...

SequelizeDatabaseError: The operation could not be executed as there is no operator that allows for

I am attempting to create a join between two tables using UUIDs (also have IDs), and the relationships between these tables are quite complex... However, I encounter an error when running the query. The first table is named users, with its UUID labeled a ...

Problem-solving modal disappearance

In my current project, I am working on a feature that involves displaying a dropdown modal after 3 minutes on the page. The modal includes an input field where users can enter digits, and upon clicking 'save', the modal should hide. Everything se ...

Angular 4 is displaying an error message indicating that the expression has been modified after being initially verified

I've been utilizing Angular Material within my Angular 4 application. There seems to be an issue when attempting to utilize the MatSnackBar in the ngAfterViewInit(). The error I encounter is as follows: ExpressionChangedAfterItHasBeenCheckedError: ...

Tips for implementing WebSockets with Play Framework

I recently downloaded Play Framework from GitHub and successfully compiled it. My goal now is to implement WebSockets using a JavaScript client along with a WebSocket controller similar to the one outlined in the Using WebSockets documentation. However, de ...

Center the span in CSS by setting its position to absolute

I am trying to create a span element positioned as absolute inside a div. The div has top and left values set. When the user inputs text, the span expands with the given text towards the right to contain it. However, I would like it to grow symmetrically o ...

Express route encountered an error with an undefined value

Here's the method declaration: exports.postRedisValue = function(req,res) { let keyRedis = req.body.key; let valueRedis = req.body.value; console.log(keyRedis); //displays as undefined if(keyRedis && valueRedis){ ...

Pop-up windows, the modern day digital version of fortune cookies

Expressing my requirement might be a bit challenging, but I will do my best. My goal is to create a web application using ASP.Net with C#. This project calls for functionality similar to the Windows popup: When a user clicks on the favorite button in IE- ...

Exporting two functions in JavaScript

Currently utilizing React, Redux, and experimenting with Material-UI integration. The example codes provided by Redux and Material-UI libraries include an 'export' statement at the end. Redux: export default connect(mapStateToProps, actions)(my ...

Transferring a zipped file between a Node.js server and a Node.js client

I am facing an issue with sending a zip file from a node.js server to a node.js client. The problem is that when I try to save the zip file, it becomes corrupted and cannot be opened. To create and send the zip file to the client, I am using the adm-zip l ...

Building a remote shell using Node.js with the ability to interpret control sequences

Currently, I am working on developing a remote shell using Node.js. Here's the code that I have implemented so far : Client var net = require('net'); var client = net.connect({port: 1234}, function(){ process.stdin.pipe(client); clien ...

Unable to retrieve the complete count of invitations made by a user

My goal is to retrieve the invites of the author of a specific command within one server. I have experimented with various solutions, but many appear outdated or incorrect. Here is my current approach: exports.run = async (client, message, args) => { ...

Error encountered when attempting to include a foreign key

I am attempting to establish a 1:1 relationship between two tables. The RefreshToken table will contain two foreign keys connected to the Users table, which can be seen in this image: https://i.stack.imgur.com/B2fcU.png To generate my sequelize models, I ...

Personalized Element Commands and features

UniquePage.html <div ng-controller="UniquePageCtrl"> <unique-custom-directive arg1="{{currentObj.name}}"></my-custom-directive> <div> in UniquePageCtrl.js (Controller) app.controller("UniquePageCtrl", ["$scope", function ($sc ...