Ways to make JavaScript cycle through a set of images

I'm having trouble trying to set up a code that will rotate multiple images in a cycle for an image gallery I'm working on. So far, I've only been able to get one image to cycle through successfully. Any help or suggestions would be greatly appreciated. I am currently studying web development in college and have a decent grasp of the basics of javascript, but struggle when it comes to creating applications.

If you'd like to take a look at my code, here is the link: jsFiddle

$(document).ready(function () {
    var img = document.images;
    // Image collection array
    var counter = 0;

    var imgArray = [];
    imgArray[0] = "http://www.zeroprox.tk/temp/images/img1.png";
    imgArray[1] = "http://www.zeroprox.tk/temp/images/img2.jpg";
    imgArray[2] = "http://www.zeroprox.tk/temp/images/img3.png";
    imgArray[3] = "http://www.zeroprox.tk/temp/images/img4.jpg";
    imgArray[4] = "http://www.zeroprox.tk/temp/images/img5.jpg";
    imgArray[5] = "http://www.zeroprox.tk/temp/images/img6.png";
    imgArray[6] = "http://www.zeroprox.tk/temp/images/img7.jpg";
    imgArray[7] = "http://www.zeroprox.tk/temp/images/img8.png";

    $("#left-arrow").click(function () {
        if (counter < 0) {
             counter = imgArray[counter] - 1;   
        } else {
             counter--;   
        }

        img[1].src = imgArray[counter];
    });
    // Previous image arrow

    $("#right-arrow").click(function () {
        counter = (counter + 1) % imgArray.length;

        img[1].src = imgArray[counter];
    });
    // Next image arrow
});

Answer №1

Here is a solution on JSFiddle

Give this code a try, it might help with your issue ;)

The problem was that you were constantly replacing the same image. This code creates a new image and removes the old one.

Furthermore, I included a div#imagelist to make it easier to access the images in JavaScript

var newImg = $(document.createElement("img"));
newImg.attr("src",imgArray[counter]);
$("#imagelist img").last().remove();
$("#imagelist").prepend(newImg);

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

HTML/JavaScript - Ways to show text entered into an input field as HTML code

One dilemma I'm facing involves a textarea element on my website where users input HTML code. My goal is to showcase this entered HTML code in a different section of the webpage. How should I approach this challenge? The desired outcome is similar to ...

Troubleshooting the onExited callback issue with Popover component in Material UI

<Popover key={element.name} classes={{ paper: classes.paper }} open={open} anchorEl={this.myRef.current} anchorOrigin={{ vertical: ' ...

How about mixing up your backgrounds with an overlay effect for a unique look?

Hey there, I'm currently working on adding random backgrounds to my website through an overlay, but I've hit a roadblock when it comes to displaying them. Here is the code I'm working with: .css / .php #intro { background: ...

The Mean Stack by Bitnami

After setting up the Mean Stack Manager, I encountered an issue. When running a command in the node terminal like console.log("Hello World"), it runs smoothly. However, if I place a Javascript sample file in any folder within the mean stack install directo ...

Hexagonal Shape with Rotating Border Gradient in CSS

Looking to create a hexagon shape with a rotating gradient border. Here's an example GIF for reference: https://i.stack.imgur.com/Ah1AO.gif I attempted using CSS only but the use of :after and :before tags proved limiting since they rely on border s ...

Error 405: Javascript page redirection leads to Method Not Allowed issue

After receiving the result from the ajax success method, I am facing an issue where the redirection to another page is being blocked and displaying the following error: Page 405 Method Not Allowed I am seeking suggestions on how to fix this as I need to ...

The dictionary of parameters includes an empty value for the parameter 'imageWidth', which is of a non-nullable type 'System.Int32'

I am facing an issue with a function that executes an ajax call to an ActionResult. It sends a base64 string of an uploaded image along with some additional parameters containing information about the dimensions of the image. The data is sent to the server ...

What can be done to improve the elegance of this jQuery function?

I am facing an issue on my webpage where I have a drop-down select box with a default value of (empty). The problem arises when the user selects an entry, and the appropriate form for that entry type should be displayed. However, there are a couple of iss ...

Adding labels to a JavaScript chart can be done by using the appropriate methods

https://i.stack.imgur.com/uEgZg.png https://i.stack.imgur.com/y6Jg2.png Hey there! I recently created a chart using the Victory.js framework (check out image 1) and now I'm looking to incorporate labels similar to the ones shown in the second image ab ...

Problems with Key Presses in Form Verification

Yesterday evening, our supervisor called me to report an issue with our app. He mentioned that when he tried to log in using a dummy password, the validation was successful. It seems that clicking on the mouse to authenticate the password was working corr ...

Is there a way for me to show "No data" when the json response in vue js is empty?

Is it possible to display a message like "No search results" when there is no data available? I am new to this and only have basic understanding. Can someone guide me on how to achieve this? Example of my JSON data when it's empty: { "status": true ...

What is the best way to make a Modal triggered by a loop embedded within a table function properly on mobile devices?

While the modal is functioning properly on desktop, it seems to be encountering issues on mobile devices. The modal appears behind the background and is confined by the boundaries of the table (tbody). Below is the code snippet for triggering the modal: ...

Use flexbox to manage the width of containers and control the wrapping of elements

Hello, I am a newcomer to utilizing flexbox in CSS. I have these "boxes" that need to maintain their width and wrap when the screen size is small. On a large screen: On a small screen: .container { margin-top: 1em; display: flex; justi ...

Recreating elements in ng-repeat using ng-click conditionally

I am attempting to swap an anchor tag with an image when clicked by the user. The code snippet I'm using looks like this: <div ng-repeat="postpart in currentPost.parts "> <div ng-if = "!postpart.isclicked"> <img ng-src= ...

What changes occurred to module file names following the process of minification?

I'm currently troubleshooting an issue with this particular code snippet: import globalComponents from './global-components'; // ... globalComponents.forEach((component) => { // eslint-disable-next-line no-underscore-da ...

Click on the header to activate the accordion link with a trigger

I am having an issue with a trigger. My goal is to make the accordions collapse not only by clicking on the link, but also by clicking on the entire header panel. Below is my header's code: <div class="accordion-head" role="tab"> <div cl ...

What's the trick to making a column that's 2/3 wide in a 34grid layout?

Is it possible to use the 34 Responsive Grid system to create a column that takes up two-thirds of the full width? Although the Grid System has equal columns settings, I'm curious how to combine or merge two columns together? <div class="containe ...

Guide to displaying a pop-up modal containing text and an image when clicking on a thumbnail image

Recently delving into Bootstrap 3, I created a thumbnail grid showcasing images related to various projects. My goal is to have a modal window pop up when clicking on an image. Within the modal, I want to display the selected image alongside some descrip ...

Tips for centering text in a react flexbox layout

Utilizing react-flexbox-grid in my project has led to the following layout: const SpicyMenu = (props) => ( <List> {props.foodItems.map(foodItem => <SpicyMenuItem key={foodItem.name} {...foodItem}/>)} </List> ); co ...

Creating a collaborative storage space within a MERN project folder

Currently, I am developing an application using the MERN stack. The structure of my project repository includes both backend and frontend components: my-project/ ├── backend/ │ │ │ . │ . │ └── package.json ├── fronten ...