What is the best way to create a slideshow that automatically starts upon loading and pauses when hovered over?

I have recently set up a div element for my slideshow. I've included a script to enable navigation using next and previous arrows. However, I am looking to add an automatic slideshow feature that stops on hover. As a beginner, I would appreciate any assistance in achieving this.

<div id="slideshow">
               <a href="#" class="slideshow-prev">&laquo;</a> 
               <ul>
                    <li><img src="images/1.jpg" alt="photo1" /></li>
                    <li><img src="images/2.jpg" alt="photo2" /></li>
                    <li><img src="images/3.jpg" alt="photo3" /></li>
                    <li><img src="images/4.jpg" alt="photo4" /></li>
                    <li><img src="images/5.jpg" alt="photo5" /></li>
               </ul>
                <a href="#" class="slideshow-next">&raquo;</a> 
            </div>
               <script>

                //an image width in pixels 
                var imageWidth = $('#slideshow ul li').width();


                //DOM and all content is loaded 
                $(window).ready(function() {

                    var currentImage = 0;

                    //set image count 
                    var allImages = $('#slideshow li img').length;

                    //setup slideshow frame width
                    $('#slideshow ul').width(allImages*imageWidth);

                    //attach click event to slideshow buttons
                    $('.slideshow-next').click(function(){

                        //increase image counter
                        currentImage++;
                        //if we are at the end let set it to 0
                        if(currentImage>=allImages) currentImage = 0;
                        //calculate and set position
                        setFramePosition(currentImage);

                    });

                    $('.slideshow-prev').click(function(){

                        //decrease image counter
                        currentImage--;
                        //if we are at the end let set it to 0
                        if(currentImage<0) currentImage = allImages-1;
                        //calculate and set position
                        setFramePosition(currentImage);

                    });

                    // Automatic slideshow function
                    setInterval(function(){
                        currentImage++;
                        if(currentImage >= allImages){
                            currentImage = 0;
                        }
                        setFramePosition(currentImage);
                    }, 5000); // Change slide every 5 seconds

                    // Stop slideshow on hover
                    $('#slideshow').hover(function(){
                        clearInterval();
                    }, function(){
                        setInterval(function(){
                            currentImage++;
                            if(currentImage >= allImages){
                                currentImage = 0;
                            }
                            setFramePosition(currentImage);
                        }, 5000); // Resume slideshow after hovering out
                    });

                });

                //calculate the slideshow frame position and animate it to the new position
                function setFramePosition(pos){

                    //calculate position
                    var px = imageWidth*pos*-1;
                    //set ul left position
                    $('#slideshow ul').animate({
                        left: px
                    }, 300);
                }
            </script>

I just created a div for my slideshow. Below I have script for make this slideshow workable using next and previous arrows. I want to make same slide to work auto slideshow and on hover it stop. Any one can help me out how do I do ? as I am beginner to this If possible, can someone please provide me with a JavaScript code that will automatically play the slide show

Answer №1

To enhance the slideshow functionality, you can use the code snippet provided below and embed it within a script tag:

let timer;
$(window).load(function(){
    timer = setInterval(function(){
        $('.slideshow-next').trigger('click');
    },5000);

    $('#slideshow').hover(function(){
        clearInterval(timer);
    },function(){
        timer = setInterval(function(){
            $('.slideshow-next').trigger('click');
        },5000);
    });
});

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 preferred method for verifying AJAX success when the server's response is either true or false?

My server response can be either true or false. I've been attempting to determine how to check for success based on the returned value being true or false using the script below: $('form[data-async]').on('submit', function(event) ...

Adding data to each span and div using JavaScript is a simple task that can be achieved easily

What is the best way to add information to each span and div element using JavaScript? $(document).on("click",".selection-state",function(){ stateid = $(this).attr("rel"); $("#my_tooltip").html(data); } e ...

Issue: Debug Failure. Invalid expression: import= for internal module references should have been addressed in a previous transformer

While working on my Nest build script, I encountered the following error message: Error Debug Failure. False expression: import= for internal module references should be handled in an earlier transformer. I am having trouble comprehending what this erro ...

Passing a variable from a jQuery function to a submitted form: the ultimate guide

I stumbled upon this code snippet online and it's exactly what I needed to learn from as a beginner using jQuery. However, I have a question about transferring or passing the value of counter that was used in the jQuery script within the HTML head tag ...

Use JavaScript to illuminate individual words on a webpage in sequence

Is there an effective method to sequentially highlight each word on a web page? I'm thinking of breaking the words into an array and iterating through them, but I'm not sure what the best approach would be. I have experience with string replacem ...

Using Four Different Colour Borders in CSS

Is it possible to create a CSS border with 4 different colors on one side? Currently, I have the following: #header { border-color:#88a9eb; } I aim to achieve a border featuring four solid colors split equally at 25% each. Can this be done? I am looking ...

What is the best way to format this <li> element so that the second line of text starts directly below the beginning of the first line, rather than below the bullet point itself?

Is there a way to align the second row of a list item directly below the text and not below the bullet point? <ul class="arrow-list"> <li>Clear and consistent brand identity</li> <li>+47.08% Increase in website registration ...

Why is it that my jquery code seems to be struggling with calculating the count accurately?

I'm currently working on restricting keyword input on my website. My goal is to automatically add a 'span' tag to any keyword entered by a user, as shown in the example html code below. Although I can limit the number of words, the count i ...

Encountering an Internal Server Error while setting up a Next.js Application

I recently decided to dive into Next.js and followed the tutorial on their official website, but unfortunately, I hit a roadblock. When I run npm run dev, I encounter the following error messages in my console and terminal: Failed to load resource: the ser ...

PHP does not automatically escape HTML special characters

Within my ZF2 application, there is a .phtml layout that includes the following code: <p>Created in 2015 <?php echo htmlspecialchars("by Jérôme Verstrynge",ENT_HTML5); ?></p> However, when I review the source of the pages returned by ...

Unable to switch. Is there an issue with the initialization of Bootstrap 5 JavaScript?

I seem to be encountering an issue with my implementation of Bootstrap 5.0.0-beta2. While I can expand my navbars and accordions successfully, collapsing them does not work as expected. It appears that the problem lies in the initialization of the JavaScr ...

Using Framework7 and AngularJS to efficiently load pages

When creating a phone application using phonegap, AngularJS, and Framework7, I encountered an issue with the page swapping functionality of Framework7. The problem arises because Framework7 injects new HTML pages into the DOM dynamically when a user click ...

Conceal a division on a webpage according to the URL of the specific

<script> function hideSearchField() { if (/menu/.test(window.location.href)) { document.getElementById('searchfield').style.display = 'none'; } } hideSearchField(); </script> I am trying to accomplish this using Jav ...

Assigning a unique date/time stamp to every MongoDB document when it is created

This is my second query regarding Node.js for today. It's getting late, and I need some assistance to quickly incorporate this function before calling it a night. I have developed a small Q&A application where I can interact with MongoDB to read and ...

What could be the reason for justify-self: flex-start not positioning the div at the bottom of a column?

I want to display a div in three levels: header, content, and footer. The content can vary in height and the footer should always be at the bottom. Here is how I have implemented it: <div class="news-content-block"> <div class=" ...

Calling a C# Webmethod using jQuery AJAX is not working as expected

I'm currently facing an issue calling a web method that I created. The problem lies in the fact that the ajax call isn't reaching my web method, which is puzzling to me because I have another web method in the same file with the same return type ...

Initiate Ant Design select reset

I am facing an issue with 2 <Select> elements. The values in the second one depend on the selection made in the first one. However, when I change the selected item in the first select, the available options in the second one update. But if a selectio ...

Contrasting createMuiTheme and getMuiTheme

When would you choose to use one over the other? What are the key differences in how they operate? ...

Creating Tailored Breakpoints with Bootstrap for a Unique Design

Currently, I am delving into the world of front-end web design and taking advantage of Bootstrap for creating a responsive layout. However, I have noticed that Bootstrap only offers 5 predefined breakpoints. I am curious to know if there is a way to cust ...

Struggling to insert a JavaScript variable into a MySQL database table using PHP and AJAX

As a newcomer to these technologies, I've been struggling all day with what I expected to be a simple task. My goal is to pass a parameter from a JS function to my PHP code using AJAX and then insert that parameter into my database. Here's the J ...