How can you create a basic slideshow without relying on jQuery to cycle through images?

Imagine you have a div containing 3 images.

Is there a way to build a basic slideshow that smoothly transitions between the images, showing each one for 5 seconds before moving on to the next one and eventually looping back to the first image without relying on jquery or any other framework?

Answer №1

(function () {
    var elements = document.getElementById('your_div').getElementsByTagName('img'),
        count = 0;
    elements[0].style.display = 'block';
    setInterval(function () {
        elements[count].style.display = 'none';
        count = (count + 1) % elements.length;
        elements[count].style.display = 'block';
    }, 5000);
}());

Sample HTML Link: http://jsfiddle.net/Zq7KB/1/

Update: Came across a more refined demonstration above that utilized .length.

Answer №2

To create a timed slideshow, you can utilize the setInterval method along with setting the src attribute of an img element:

window.onload = function() {
    var slides = [ "path_to_image_one",
                   "path_to_image_two",
                   "path_to_image_three" // ...
                 ],
        index = 0,
        timer = 0;

    // Display the initial slide
    showNextSlide();

    // Switch to the next slide every five seconds
    timer = setInterval(showNextSlide, 5000);

    // Function to display the next slide   
    function showNextSlide() {
        if (index >= slides.length) {
            index = 0;
        }
        document.getElementById('theImage').src = slides[index++];
    }
};

Ensure your image markup is as follows:

<img id="theImage" src="path_to_initial_placeholder">

Keep in mind that the timer handle is stored in timer, which can be used to cancel the timer if necessary to halt the slideshow.

Update: If you need to fetch images from a specific div instead of hardcoded paths, here's an updated version that dynamically populates the slides array by extracting direct child IMG elements from a div with the ID "theDiv":

window.onload = function() {
    var slides = [],
        index = 0,
        timer = 0,
        node;

    // Retrieve the slides
    for (node = document.getElementById('theDiv').childNodes;
         node;
         node = node.nextSibling) {
        if (node.nodeType == 1 && node.tagName == "IMG") {
            slides.push(node.src);
        }
    }

    // Display the initial slide
    showNextSlide();

    // Switch to the next slide every five seconds
    timer = setInterval(showNextSlide, 5000);

    // Function to display the next slide    
    function showNextSlide() {
        if (index >= slides.length) {
            index = 0;
        }
        document.getElementById('theImage').src = slides[index++];
    }
};

Answer №3

To control the <div>, you'll need to first identify it by its "id" attribute:

var mainDiv = document.getElementById("mainContainer");

From there, a timer can be set up to rotate through different images:

(function(div, delay) {
  var index = 0;
  var images = div.getElementsByTagName('img');
  function displayOne() {
    for (var i = 0; i < images.length; ++i)
      images[i].style.display = 'none';
    images[index].style.display = '';
    index = (index + 1) % images.length;
    setTimeout(displayOne, delay);
  }

  displayOne();
})(mainDiv, 4000);

Answer №4

let images = new Array('/img/1.jpg', '/img/2.jpg', '/img/3.jpg');

setTimeout("displayNextImage()",5000);

function displayNextImage()
{
let container = document.getElementById('image_container');
container.innerHTML = "<img src='" + images[i] + "' />";
if(i==2) { i = 1; }else { i = i + 1; }
}

Answer №5

Although this answer seems straightforward, there were a few mistakes that I noticed. Instead of using setTimeout, the correct function to use in this case would be setInterval. Additionally, the initial index was not properly set. I also made an adjustment to ensure that the first image loads immediately.

var images = new Array('imgs/18/P1050294-XL.jpg', 'imgs/18/P1050293-XL.jpg', 'imgs/18/P1040984-XL.jpg', 'imgs/18/P1040983-XL.jpg', 'imgs/18/P1040982-XL.jpg');

var path = 'mypath';

document.getElementById('slideShow').innerHTML = "<img width='600px' src='" + path + images[0] + "' />";  // Load First image
var i = 1;  // Set counter to the second image for the first iteration of the loop

setInterval("show_next(path)", 5000);

function show_next(path)
{
var container = document.getElementById('slideShow');
container.innerHTML = "<img width='600px' src='" + path + images[i] + "' />";
if(i === 4) { i = 0; } else { i = i + 1; }
}

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

Import a picture file into Photoshop and position it at a designated location

I need assistance with developing a function that can load an image and position it at specific x, y coordinates in Photoshop. Below is the code I have so far: var docRef = app.activeDocument; function MoveLayerTo(fLayer, fX, fY) { var Position = fLaye ...

Enhancing Angular 4 classes with dependency injection techniques

Currently utilizing angular 4 and angular cli for my project development. I have created some classes that serve as the base for my components! However, as the constructors of these classes grow during development, I find myself in a phase where I need to ...

Are we retrieving multiple APIs the right way?

Looking for some guidance on fetching two APIs in React. I have created two functions to handle this task and called them simultaneously within another function. Should I stick with this approach or move the API calls to componentDidMount? Additionally, I& ...

Change the controller's classes and update the view in Angular

In my angular application, I have a popup window containing several tabs. These tabs are styled like Bootstrap and need to be switched using Angular. The code for the tabs is as follows (simplified): <div class="settingsPopupWindow"> <div> ...

Two states each offering a distinct perspective

I am currently working on modularizing my application using angular-ui-router to create a website with two states: main and checkout. In the main state, I want to have multiple "section" tags defined as ui-view items. However, it seems like there is an iss ...

Tips on adding line breaks after periods that are not at the end of a sentence in HTML text nodes with regular expressions

Looking to craft a regex that can identify all periods not enclosed in quotes and not followed by a '<'. This is for the purpose of converting text into ssml (Speech Synthesis Markup Language). The regex will be utilized to automatically inse ...

Edit the information within an element

Seeking assistance in swapping out text within anchor tags (<a>here</a>) on a website built with Wordpress. Unable to alter the HTML directly, so looking to use Jquery or PHP. The challenge lies in the lack of classes or IDs for the anchor tag ...

The pdfkit library seems to have an issue where it is failing to properly embed images within the

Currently, I am working on using PDFkit along with node.js for converting an HTML webpage into a PDF format. The HTML page contains multiple image tags within the body tag. Unfortunately, when I convert the HTML to PDF, the resulting page appears complete ...

Chrome geolocation feature does not display the permission popup for JavaScript

After the latest Chrome update, we have noticed that the popup to Allow/Block accessing a user's location from a website is no longer appearing. We tested this on Edge, Firefox, and different mobile devices, where it seems to be working fine. Current ...

Having trouble retrieving an object from an event handler in ReactJS

const question = { quest : "What is my age?", answers : [16,15,21,30], correct : 21, } validateAnswer(){ let usersResponse = document.getElementById('ans-1').textContent; let response = this.question.correct; if(usersResp ...

AngularJS implemented to trigger a popup alert after a certain duration of time has elapsed since the

Can we create a popup alert that says "Error Contacting Server" when the http request does not receive any response? .controller('items_ctrl',['$scope','$http',function($scope,$http){ $scope.shop_id=localStorage.getItem(" ...

What is the most common method for creating a dropdown menu for a website's navigation?

Is there a common approach to creating an interactive drop-down navigation menu in the industry? I have searched on Google and found multiple methods, but as a student working on my first big web project, I am hoping to find a standard practice. I don&apo ...

Using a callback function with jQuery in a focus event

Is there a way to ensure that a callback function inside a focus() is only played once while the element has focus? For example, in the code snippet below, the alert('ok') will continue to be triggered as long as the textarea maintains focus. Is ...

Having a problem with the xmlhttprequest, not confident if it is being called correctly

I encountered a problem with the code I have where a user selects a sales center and it should trigger a currency change. Both selections are dropdowns, but when I choose a sales center, I receive an error saying ReferenceError: makeRequest is not define ...

Tips on ensuring the <script> section of a Vuejs single file component loads prior to the <template> section

After posing my query here, I have come to the realization that the root of my problem might be due to the template loading before the script. This causes an error when it encounters an undefined variable, halting the script execution. The issue could pote ...

Guide on setting up a shortcut key for an input field

Currently, I have a collection of images each with its own HTML page. I added an input button that when clicked, takes you to the next image. However, I would like to enhance user experience by allowing them to use keyboard arrows for navigation. Being new ...

If you invoke revokeObjectURL, Chrome will fail to display Blob images

-----update------ After some investigation, I found that commenting out window.URL.revokeObjectURL( imgSrc ); fixed the issue in all browsers. It seems like Chrome was revoking the URL too early. I am curious to understand why this behavior occurs, and if ...

Is there a proper method for populating an HTML text with values from a form?

As a newcomer, I could really use some guidance here :) I'm trying to populate text with various words, numbers, and calculation results from a form. This is my initial attempt for just one field/word, and it appears to be functioning correctly. Do y ...

An error occurred with the datepicker: Unable to connect to 'bsValue' as it is not recognized as a property of 'input'

Despite importing DatepickerModule.forRoot() in my Angular unit test, I am encountering the following error: Error: Template parse errors: Can't bind to 'bsConfig' since it isn't a known property of 'input'. (" ...

Webpack has successfully built the production version of your ReactJS application. Upon review, it appears that a minified version of the development build of React is being used

Currently, I am implementing Reactjs in an application and the time has come to prepare it for production. In my package.json file, you can see that there is a "pack:prod" command which utilizes webpack along with a specific webpack.config.js file to build ...