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

What is the best way to manage numerous asynchronous post requests in AngularJS?

$scope.savekbentry = function (value) { console.log('save clicked'); console.log(value); console.log($scope.kbentry.kbname); $scope.kbentry.mode = value; var kbname = $scope.kbentry.kbname; var kbd ...

Issue with event.stopPropagation() in Angular 6 directive when using a template-driven form that already takes event.data

I am currently developing a citizenNumber component for use in forms. This component implements ControlValueAccessor to work with ngModel. export class CitizenNumberComponent implements ControlValueAccessor { private _value: string; @Input() place ...

To give an element a class in Javascript (without using jQuery) if it is currently hidden

Apologies if this question is not perfect, as I am still learning. I have been struggling to figure out how to add a class to an ID when the class is hidden using pure JavaScript (without jQuery). Below are my attempts so far: function hidekeep() { ...

Attempting to parse the data within the success function consistently fails

$.ajax({ type : 'GET', url : 'dialog.php', data: { champion_name:champion_name }, dataType: "text", success : function(data){ alert(data); var dataStr = $(data).find('h2').html() ...

Unable to run the method in the parent component from the child component

I am attempting to trigger a method to run on a parent component when a button within one of its child components is clicked. I am utilizing single file components with Webpack. Below is the code for the child component: <template> <button v-on ...

`Finding and including the additional object in JavaScript`

Seeking guidance on how to manipulate a specific object in Javascript, I have successfully retrieved the object based on a filter, but I am unsure how to append `'in'='bank' and 'out'='bank'` of non-filtered ids to ...

Incorporate my personalized icons into the button design of ionic 2 actionSheet

I'm struggling to figure out how to incorporate my personal icon into the actionSheet feature of ionic 2/3. presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Mode', buttons: [ { ...

Spacing issues while utilizing the <textarea> element

<tr> <td> <b>Escalation: </td></b> <td> <TextArea name='escalation' onKeyDown=\"limitText(this.form.escalation,this.form.countdown,100);\" onKeyUp=\"limitText ...

"Utilizing jQuery to Send POST Requests on Rails - Dealing

Currently, I am running a JavaScript game from file:// and attempting to send a post request to a localhost Rails server in order to add a new high score. In my JavaScript: highScoresEntryView.keyHandlers = function() { var that = this; this.pa ...

Exploring the possibilities of socket.io-client in combination with Vite.js and Vue for seamless real

I am currently diving into socket.io for my upcoming Vue project, but I seem to be encountering some issues. Interestingly, everything works smoothly when I use vue-cli, however, I prefer working with Vite.js due to its speed and customization options. Unf ...

Effortless signing out using AJAX, Zend Framework, and jQuery

Is there a way to invoke the logout action upon a user clicking the signout link without needing a page refresh or redirecting? Any assistance would be greatly appreciated. Thank you! ...

Issue with Checkbox Functionality Between Parent and Child Components in React.js

In the main component, I have four checkboxes. My goal is to display a value from a function in the child component based on whether each checkbox is checked or not. export default class App extends Component { constructor(props) { super(props); ...

Exploring the effectiveness of React Hook Form using React Testing Library

My Component includes a form that, upon submission, utilizes Apollo's useLazyQuery to fetch data based on the form values. The form in the component is managed by React Hook Forms, with the handleSubmit controlled by RHF. <FormContainer onSubmit= ...

Tips for keeping my wordpress menu at the forefront

This piece of code is responsible for controlling the main menu on my website. Currently, it's set up so that when I scroll down, the menu disappears, and when scrolling up, it reappears. However, I would like the menu to always remain displayed at t ...

Is there a way to extract the properties of a CSS class from a stylesheet and convert them into a hash using JavaScript or jQuery?

I am exploring a way to extract key value pairs from a CSS stylesheet related to a specific class or id into a JavaScript object for data accessibility. It is important to mention that I do not intend to apply this class directly to any DOM elements. In ...

Generate a series of rotations ranging from -60 to 60 using d3.cloud

I need help replicating the word cloud feature found on for my website. After studying examples and referencing a Stack Overflow answer, I put together the following code: var fill = d3.scale.category20(); var layout = d3.layout.cloud() .size([900, ...

Tips for clearing a textbox value in JQuery after a 5-second delay

I attempted the following: <script type="text/javascript"> $(function() { $("#button").click( function() { alert('button clicked'); // this is executed setTimeout(function() ...

The content loses functionality once I add an overlay color to the background image div

I'm facing an issue with a div that has a background image, text, and a button in the center. Whenever I add an overlay color on top of the background image, the text and button seem to be disabled or unclickable. My goal is to ensure that the Read M ...

Is there a way to deactivate the ctrl and click event using jQuery UI?

I am encountering an issue with a table that is utilizing both the jquery-ui.min.js and jquery.treeTable.js. Whenever I press ctrl and click somewhere on the table, the cell gets selected (a blue border appears), which is not the expected behavior. Is ...

Troubleshooting Vue 3 Computed Property Not Updating

I'm currently facing a challenge while developing a login form using Vue 3. I am having difficulty in getting the state to update 'realtime' or computed. When attempting to login a user from the template, the code looks like this: <button ...