Error in JavaScript Slideshow

I am attempting to create a slider that changes with a button click. Below is my JavaScript code:

    var img1=document.getElementById("p1");
    var img2=document.getElementById("p2");
    var img3=document.getElementById("p3"); 

    function slide(){
    var count=0;
        if(count==0){
            img1.style.display= "none";
            img2.style.display= "block";
            count=1;
        }
        if(count==1){
            img2.style.display= "none";
            img3.style.display= "block";
            count=2;
        }
        if(count==2){
            img3.style.display= "none";
            img1.style.display= "block";
            count=0;
        }
    }

var btn=document.getElementById("btn");
btn.onclick=slide;

Below are my CSS codes for the 3 images:

#p1{
    display:block;
}
#p2{
    display:none;
}
#p3{
    display:none

Despite setting p1 to block and others to none, nothing changes. However, when I make p2 or p3 block and others none, the slider goes back to p1 and doesn't change again. What could be causing this issue? Here is the HTML of the div:

<div id="second">
<img class="mySlides" id="p1" src="rbt.jpg">
<img class="mySlides" id="p2" src="scv.jpg">
<img class="mySlides" id="p3" src="hml.jpg">
<button id="btn">Next</button>
</div>

Answer №1

To properly execute this code, it is essential to declare the variable outside of the function and incorporate the use of else if statements.

let counter = 0;
function slideshow(){
    if(counter == 0){
        image1.style.display = "none";
        image2.style.display = "block";
        counter = 1;
    } else if(counter == 1){
        image2.style.display = "none";
        image3.style.display = "block";
        counter = 2;
    } else if(counter == 2){
        image3.style.display = "none";
        image1.style.display = "block";
        counter = 0;
    }
}

Answer №2

When I change p1 to block and hide the others, there is no difference. However, if I hide p2 or p3 and show p1, the slider moves to p1 but does not change again.

What needs to be altered? Whenever your method is called, what occurs initially?

    function slidee(){
      var sl=0;

      if(sl==0){
        img1.style.display= "none";
        img2.style.display= "block";
        sl=1;
      }
      ...
    }

What seems to be the issue in this scenario?

Every time the variable sl is set to 0 with each function call.

    var sl=0

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

Printing without sufficient paper will result in an incomplete printout

https://i.stack.imgur.com/jNlRr.jpg I am facing an issue with printing the last column "Potensi". The text in this column is not fully printed. How can I resolve this problem? I am using PHP. Thank you ...

Unable to show the response from an HTML servlet using Ajax and qTip2

I am having an issue where I am trying to display text (or html) received from a servlet response in a qTip2 tooltip within a jsp page. Despite verifying that the servlet is being invoked and returning text using Firebug, I encountered an error when attemp ...

JavaScript: Code for creating an overlay component

As someone who is new to javascript and Jquery, I have very little understanding of what I am doing. I have been relying on trial and error to make progress so far. While I am aware that users have the ability to disable javascript, I prefer not to use PHP ...

Setting a menu item as active in a SvelteKit app: A step-by-step guide

I encountered an issue with the main navigation menu in my sveltekit application. The problem is that when the app is loaded or refreshed, the active menu item corresponding to the current URL is not set. After struggling to find a solution online, I manag ...

React and Material-UI issue: Unable to remove component as reference from (...)

My React components are built using Material-UI: Everything is running smoothly MainView.js import React, { Component } from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { List, ListItem } from ...

Enhance your theme property in Styled Components by incorporating numerous style properties

Currently, I am delving into the world of styled components for a fresh project and exploring the theming capabilities it offers. I am finding it challenging to determine the best practice for adding multiple style properties to a single object, essentiall ...

Is react-particles-js still compatible for me to integrate?

I recently discovered that the package found here: https://www.npmjs.com/package/react-particles-js has been deprecated. Can I still utilize this package? The codes in question can be viewed at: https://codesandbox.io/s/particle-js-background-forked-woypk ...

Querying val results in an empty string being returned

In my application, I have the following HTML code snippet: <tr style="cursor:pointer;"> <td>100101</td> <td>Monkey</td> <td>Nuts<td> <td>Cow</td> <td>Soup</td> <t ...

How are these background images able to remain in a fixed position like this?

Trying to name this question correctly was a bit tricky. Hopefully I got it right. I have a new client and they want their website to have a similar feel to . If you check out the index page and scroll down, there's this cool 'smooth animation& ...

The Material UI read-only rating component fails to update even after the data has been successfully loaded

I have a rating component in my child component, and I am passing data from the parent component through props. However, there seems to be an issue with the MUI rating value not updating when the data is ready for viewing. https://i.sstatic.net/bqSfh.jpg ...

Displaying various Vue components within Laravel 6.x

After diving into Laravel and Vue, I managed to put together a navigation component as well as an article component. The problem I'm facing is that although my navigation vue component is visible, the article component seems to be missing. Reviewing ...

Tips for automatically closing a dropdown menu when it loses focus

I'm having some trouble with my Tailwind CSS and jQuery setup. After trying a few different things, I can't seem to get it working quite right. In the code below, you'll see that I have placed a focusout event on the outer div containing th ...

Utilize JavaScript to extract an image from an external URL by specifying its attributes (id, class)

Is it possible to fetch an image from an external website by using its CSS id or class in conjunction with JavaScript/jQuery's get methods? If so, could someone provide guidance on how to achieve this task? ...

What are the risks associated with allowing user-generated HTML or Javascript code on a website?

Is it really dangerous to allow users to edit HTML with Jinja2 templates and access some server-side variables that will be rendered later? I know Google uses Caja Compiler to sanitize and sandbox HTML served from Google Apps Script. Should I be concerned ...

Deleting a specific element in React: Step-by-step guide

Having an issue with the handleDelete() method in DisplayList.JSX where it is deleting the first element instead of the selected element. How can this be resolved? Github Display.jsx import {DisplayList} from './DisplayList'; class Display e ...

Is there a way to insert a value into the input field using JQuery or JavaScript?

After reading my previous post on posting values into an input box, a commenter suggested using JQuery or Javascript. For more code and information, please refer to the link provided above. <label>Date</label>:&nbsp&nbsp <input sty ...

Having Difficulty Modifying the CSS Styles of a Specific Class

I've been struggling with a CSS styling issue for some time now. The problem lies in targeting the class for the thumbnail preview of vue2-dropzone (which shares similar properties with dropzone.js based on documentation). Each time I upload an image, ...

Passing a variable through jQuery onClick event to a URL via GET request and subsequently loading the content of

After successfully passing variables through AJAX calls via onClick to a PHP file and loading the results on the initial page, I now face the challenge of passing a variable analogously via onClick to a PHP file but this time I need to either open a new wi ...

JavaScript: Exporting and Utilizing a Function within a Model.js File

Coming from a background in PHP OOP development, I am aware that there are various methods to create classes in JavaScript. I require assistance from a JavaScript developer to resolve this particular issue. Here is the situation: I am building an AWS lamb ...

What steps should be taken to retrieve the contents of a file that has been chosen using the browse

You have successfully implemented a browse button that allows the user to navigate the directory and choose a file. The path and file name are then displayed in the text element of the Browse button complex. Now, the question arises - how can I extract dat ...