shahrzad ar
shahrzad ar

Reputation: 41

How to write a loop for automatic slideshow?

I want to add a loop to a slideshow but I'm new to jQuery and don't know how to do it. and here are the codes:

$(function(){
    $("#slide_container").mouseout(function(){

        /*a loop here that change the images automatically when the mouse is not inside the div,
        get the index of the image and add to it like a for loop (i = 0; i < slides.length; i++) 
        but I still don't know which var should I add and how mouseout works.*/

    });

    $("#slide_container").mouseover(function(){
        $('#nextBtn').on('click', function(){
            console.log('clicked');
            var currentImg = $(".active");
            var nextImg = currentImg.next();

            if(nextImg.length){
                currentImg.removeClass('active').css('z-index', -10);
                nextImg.addClass('active').css('z-index', 10);
            }

        });

        $('#prevBtn').on('click', function(){
            console.log('clicked');
            var currentImg = $(".active");
            var prevImg = currentImg.prev();
            if(prevImg.length){
                currentImg.removeClass('active').css('z-index', -10);
                prevImg.addClass('active').css('z-index', 10);
            }

        })

Upvotes: 1

Views: 53

Answers (1)

Nijeesh Joshy
Nijeesh Joshy

Reputation: 1481

you can use setInterval. to execute a piece if code continuously over a inertial interval

you can trigger the click on the buttons to forward the slid

let s_interval = null;
const DELAY = 1000 //1s between each transition

$("#slide_container").mouseout(function(){
   const next_button = $('#nextBtn')
   s_interval = setInterval(()=> next_button.click(),DELAY)
});

$("#slide_container").mouseenter(function(){
   clearInterval(s_interval)
});

Upvotes: 2

Related Questions