The initial click does not trigger the function

Hey there, I'm pretty new to JavaScript and I've run into an issue with my slides. Everything seems to work fine, but only after the second click. When I added a console log in my function, it appears on the first click, however the if/else statement doesn't kick in until the second one. Can't seem to figure out what's going wrong.

let index = 0;

function previousPage () {
    console.log ('previous');
    initialize();
    if (index === 0){
        index = spContainer.length;
        spContainer[index-1].style.display = 'flex';
        index--;
    } else {     
        spContainer[index-1].style.display = 'flex';
        index--;
    }
}

function nextPage () {
    console.log ('next');
    initialize();
    if (index === spContainer.length){
        index = 0;
        spContainer[index].style.display = 'flex';
        index++;
    } else {
        spContainer[index].style.display = 'flex';
        index++;
    }
}

function initialize () {
    spContainer.forEach (x => x.style.display = 'none');
}

Answer №1

After declaring let index = 0;, you proceed to access spContainer[index-1] resulting in a value of undefined.

Answer №2

Firstly, your comparison statement is incorrect -

if (index === spContainer.length) {}
, it should actually be
if (index === spContainer.length - 1) {}
because the length starts at 1 and the index starts at 0.

I'm also confused about how you are using forEach with spContainer. It doesn't seem feasible.

My suggestion would be to rethink the entire logic in a slightly different manner. Consider this approach:

const slides = document.querySelectorAll(".slide"); // select all slide elements
let index = 0;
const maxIndex = slides.length - 1;

function increaseIndex() {
  if (index === maxIndex) {
    index = 0;
  } else {
    index++;
  }
}

function decreaseIndex() {
  if (index === 0) {
    index = maxIndex;
  } else {
    index--;
  }
}

function hideAllSlides() {
  for (let i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
}

function render() {
  slides[index].style.display = "flex";
}

function switchToPrev() {
  hideAllSlides();
  decreaseIndex();
  render();
}

function switchToNext() {
  hideAllSlides();
  increaseIndex();
  render();
}

Hopefully, this new approach will be beneficial!

Answer №3

If you want to streamline the process, consider implementing a single function that can move forward or backward based on a parameter. This approach simplifies the logic and makes testing more reliable. By determining the new index value and setting its display only once, you can avoid errors. To navigate to the next page, use movePage(true), and for the previous page, use movePage(false).

The initial code had the issue of changing the index value after setting the flex, potentially causing the wrong element to remain selected. The revised code provided below is more direct and easier to test/debug. Remember, it is crucial to set the correct index value before adjusting the display style to 'flex'.

const spContainer = [{style: {}},{style: {}},{style: {}}];
let index = 0;

function movePage(forward) {
    spContainer.forEach (x => x.style.display = 'none');
    index += forward ? 1 : -1;   // update index accordingly
    if (index < 0) {
        // go back to the last item if negative index
        index = spContainer.length - 1; 
    } else if (index >= spContainer.length) {  
        // return to the beginning if index exceeds length   
        index = 0;
    }
    spContainer[index].style.display = 'flex';

    console.log (forward?'next':'previous',index);
    console.log(spContainer);
}

function nextPage() { movePage(true); }
function previousPage() { movePage(false); }

previousPage(); // moving previous from index 0 should lead to index 2
nextPage();     // navigating next should take us back to the start (index 0)
nextPage();     // another next operation will bring us to index 1

Answer №4

The issue arises when you fail to update the variable index before utilizing it:

spContainer[index].style.display = 'flex';
index++;

For instance, if we assume that index = 0, then the element spContainer[0] will be visible upon page load.

Upon the first click, you modify the display setting for the element spContainer[0] to flex. However, since index remains at 0, this change is redundant and goes unnoticed.

Subsequently, you increment the value of index using index++, setting it to 1.

On the second click, you alter the display property of spContainer[1] to flex, as index was updated to

1</code previously.</p>

<p>Ensure that you update <code>index
prior to its usage:

let index = 0;

function previousPage () {
    console.log ('previous');
    initialize();
    if (index === 0){
        index = spContainer.length - 1; 
    } else {
        index--;
    }
    spContainer[index-1].style.display = 'flex';
}

function nextPage () {
    console.log ('next');
    initialize();
    if (index === spContainer.length - 1) {
        index = 0;
    } else {
        index++;
    }
    spContainer[index].style.display = 'flex';
}

function initialize () {
    spContainer.forEach (x => x.style.display = 'none');
}

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

Collecting user data input when a button is clicked

I am a beginner in the world of Angular and currently working on developing a simple to-do list application. My goal is to store the description, start time, and end time input by the user as an object in an array when the user clicks a button. Initially, ...

Chrome not displaying scrollbar when using overflow-y property set to scroll

I am experiencing an issue with the scrolling functionality in Chrome version 84.0.4147.89. I have a div that is set to overflow-y:scroll;, but unfortunately, the scroll bar is not visible. This poses a challenge for users without a mouse or touchscreen as ...

How can we ensure that Protractor's ElementArrayFinder 'each' function pauses until the current action has finished before moving on to the next iteration?

Currently, I am facing an issue while trying to utilize an 'each' loop in my Angular 8 app's end-to-end tests using protractor. Within my page object, I have created a method that returns an ElementArrayFinder. public getCards(): ElementArr ...

Having trouble with SCSS in Angular 4 CLI after adding new CSS styles?

After successfully creating a fresh Angular project using the Angular CLI for Angular 4, I decided to generate it with SCSS: ng new myproject --style=sass Everything went smoothly until I attempted to add some CSS code. For instance, when I added the fo ...

Double rendering issue with dynamic Vue components

In my dashboard, I am incorporating dynamic components. The issue is that the only dynamic component I have right now is being rendered twice when it should not be. I have attempted conditional rendering, but to no avail. Although I can share some code h ...

Using TypeScript to Trigger Events in Three.js

After recently diving into Typescript, I encountered an issue when using EventEmitter from the ThreeJS library. Whenever I attempt to trigger an event: const event: THREE.EventDispatcher = new THREE.EventDispatcher(); event.addEventListener('test&apo ...

Let's design a doughnut-style arc chart using the Chart.js plugins

My goal is to design a chart similar to the ones shown in the links below. https://i.sstatic.net/pcyIj.png https://i.sstatic.net/6ZaIZ.png Currently, I have successfully achieved displaying the value in the center using a doughnut chart, but I am strugg ...

What is the best way to generate a dynamically interpolated string in JavaScript?

I'm currently developing a reusable UI component and am exploring options to allow the user of this component to provide their own template for a specific section within it. Utilizing TypeScript, I have been experimenting with string interpolation as ...

Storing Checkbox Value and Name in an Array using React JS

I'm experiencing an issue with the checkbox. I need to capture the value and name data in array format for further processing. Checkbox Example: <input type="checkbox" id="Honda" name="A1" value="Honda" onCl ...

Display logo when website has been scrolled

On my website, I want to display a logo in the header only when the site has been scrolled. I attempted to accomplish this with JavaScript: if(document.getElementById("div").scrollTop != 0){ document.write("<img src='logo.jpg'>"); } How ...

Tips for creating a smooth transition between background colors within a div

Is there a way to smoothly transition between background colors within a div element? I've been struggling with my code and couldn't find a solution. Any help would be greatly appreciated. Thanks in advance. $(document).ready(function( ...

Having trouble with a fixed element that won't scroll?

Code Example: <div id="tmenu" style="direction:rtl;"> <img src="assets/imgs/menu/all.jpg"/> <img src="assets/imgs/menu/sweets.jpg"/> <img src="assets/imgs/menu/main meals.jpg"/> <img src="assets/imgs/menu/ma5bozat.jpg"/& ...

Navigate to the AngularJS documentation and locate the section on monitoring data changes after a dropdown selection

Just starting out with AngularJS and Stack Overflow, so I hope I am asking this question correctly. I am working on a single-page application with editable text inputs. Two select drop-downs are used to control which data is displayed - one for time perio ...

Unable to retrieve property values from an array containing objects

I am encountering an issue with my Angular + ngrx setup, and the following output is displayed in the console: {status: true, rows: 1, data: Array(1)} data: Array(1) 0: {id: "Q", description: "QQQQQ", is_active: true, created_at: " ...

The HTML and script tags are failing to connect

I recently started learning angularjs by watching the Egghead.io videos. However, I encountered an issue where I couldn't link my JavaScript page to my HTML page. my-index.html <!DOCTYPE html> <html> <head> <title>Angular ...

Tips for Incorporating xmlhttp.responseText in If Statements

This is the code snippet from my save_custLog_data.php file: <?php $a = $_GET['custEmail']; $b = $_GET['pswrd']; $file = '/home/students/accounts/s2090031/hit3324/www/data/customer.xml'; if(file_exists($fi ...

Unlocking location data in React Router-DOM 6: A step-by-step guide

I am currently working on implementing a 'forgot password' feature, where I am attempting to transfer the email data from the 'login page' to the 'forgot password' page using a Link element. However, I am encountering an issu ...

What is the best way to apply a border to the entire vertical line in a Bootstrap table?

I have utilized bootstrap to create the table displayed below. View image here I am looking to incorporate a vertical red line similar to the one shown in the image below. Additionally, I would like to add a drop shadow along with the red line. View ima ...

What is the correct way to link to a SCSS file within a component's directory?

The structure of my directories is as follows: stylesheets ..modules ...._all.scss ...._colors.scss ..partials ...._all.scss ...._Home.scss ..main.scss In the _Home.scss file, I have the following: @import '../modules/all'; .headerStyle { c ...

development of MapLayers with rails and javascript

As a newcomer to RoR, I am encountering an issue that seems to be eluding me. I attempted to replicate the example application found on the mapLayers GitHub repository at https://github.com/pka/map_layers/wiki. However, all I see is the JavaScript code gen ...