Creating an image slider that pauses on mouse hover

Here is a code snippet that I'd like to share

<body>
    <div id="slideshow">             
       <div>
           <img src="assets/images/home-banner.jpg" width="995" height="421" alt=""/>
       </div>
       <div>
           <img src="assets/images/banner1.jpg" width="995" height="421" alt=""/> 
       </div>
       <div>
           <img src="assets/images/home-banner.jpg" width="995" height="421" alt=""/> 
       </div>
       <div>
           <img src="assets/images/banner1.jpg" width="995" height="421" alt=""/> 
       </div>
       </div>
<script>
    $("#slideshow > div:gt(0)").hide();
       setInterval(function() { 
         $('#slideshow > div:first')
          .fadeOut(1000)
          .next()
          .fadeIn(1000)
          .end()
          .appendTo('#slideshow');
    },  3000);
</script>
</body>

Answer №1

Initially, implementing this with your code can be a bit challenging. It would be better to reformat it as a function responsible for sliding images. Let's assume this function is named animate_slider(). To pause the animation on mouseover, you simply need to clear the interval using the following snippet:

var time = setInterval("animate_slider()", 3000);
$('div#slideshow').mouseover(function(){
    clearInterval(time);
});

Answer №2

Check out this jQuery code snippet below and let me know if it functions correctly:

$(document).ready(function() {

    var timer;

    $("#slideshow > div:gt(0)").hide();

    $("#slideshow")
        .mouseenter(function() {
            if (timer) { clearInterval(timer) }
        })
        .mouseleave(function() {
            timer = setInterval(function() {
                $("#slideshow > div:first")
                    .fadeOut(1000)
                    .next()
                    .fadeIn(1000)
                    .end()
                    .appendTo("#slideshow");
            }, 2000);
        })
        .mouseleave();


});

The setInterval() method returns an intervalID that can be used to clear the current interval/timeout with clearInterval(). You can also view a working demo on FIDDLE DEMO

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

Tips for including a Places Autocomplete box within an InfoWindow on Google Maps

I am currently working with the Google Maps Javascript API v3 and I am facing a challenge. I want to integrate a Places Autocomplete box inside an InfoWindow that pops up when a user clicks on a marker. I have successfully created an autocomplete object a ...

Why isn't the click event triggering MVC 5 client-side validation for ajax posts?

To incorporate client-side validation with a click event for ajax posts, I followed a guide found at the following URL: Call MVC 3 Client Side Validation Manually for ajax posts My attempt to implement this involved using the code snippet below: $(&apos ...

Finding out the specific row that was clicked in a Jquery Mobile listview

I've searched everywhere and can't find a solution. How can I retrieve the value of a row tapped in a listview? This could be anything from the name to the index within the object. Currently, I have a function handling the tap event. I need to pa ...

Perform a search within an iframe

Despite the fact that iframes are considered outdated, I am attempting to create a browser within an HTML browser. I have implemented a search bar that opens the typed input in a new window which searches Google. However, I would like to modify it so that ...

The art of sketching precise lines encircling a circular shape through the

What is the best way to use a for loop in JavaScript to draw lines around a circle, similar to those on a clock face? ...

Tips for displaying a sub-menu upon hovering

I am attempting to display the list of sub-menu items when hovering over the main menu item. I have tried using the following CSS code, but it did not work as expected. Any assistance will be greatly appreciated. CSS: summary.header__menu-item.list-menu__ ...

How can we implement a function on every table using jQuery?

I have created a custom jQuery function for implementing pagination. However, I encountered an issue where when I load the function on a page with multiple tables, the pagination system gets applied to all tables. This means that the number of pages refle ...

Loading Ajax content into div (Wordpress) without pre-loading the font can cause display issues

Currently, I'm implementing a JavaScript function within Wordpress using Ajax to load the content of a post into a modal div when specific elements are clicked. Here is an example of how the JS function appears: function openProjectModal($that) { ...

Adjust the size of child divs in relation to their parent divs using jQuery

I am working with 4 divs and trying to adjust the size of the inner divs in relation to the parent divs dynamically. I have added a .top class, but I'm unsure if it is necessary or beneficial. Here is my fiddle for testing purposes: http://jsfiddle.n ...

Tips for preventing harmful messages in a chat room app

As I am working on a chat room website, users are able to input any content they want into the entry field and then send it to all online users. However, I have concerns about security - what if malicious individuals try to inject harmful HTML or JavaScrip ...

Switching the navigation menu using jQuery

I am looking to create a mobile menu that opens a list of options with a toggle feature. I want the menu list to appear when the toggle is clicked, and I also want to disable scrolling for the body. When the toggle menu is clicked again, the list should c ...

jQuery: The ultimate solution for preventing any interruptions while waiting for Ajax requests to finish

Have you heard of jQuery? It's a powerful tool. Imagine this: You have a signup form where users input their domain. As soon as they finish typing, an Ajax call is made to check if the domain is available. This validation process can sometimes take ...

The success callback function of the jquery.form.js plugin does not execute properly in Internet Explorer

Why is the jquery.form.js plugin fileupload success callback function not working in IE? The fileupload success callback works in Chrome, Firefox, and Safari. I'm puzzled as to why the "SUCCESS callback function" does not work in IE (including IE9, ...

When new text is added to Div, the first line is not displayed

One of the divs on my page has an ID of "TrancriptBox" and contains multiple lines of text. When I scroll through it on my iPad, everything works fine. However, if I scroll and then change the text within that div, it doesn't display the first line o ...

When I attempt to utilize the API, the JavaScript implementation of a <script src=...> element seems to interfere

Within one of my HTML files, I encountered the following line near the top: <script src="//maps.google.com/maps/api/js?key=apikey"></script> The API key is currently hardcoded in this file, but I would like to use a configuration option store ...

Utilizing Material-UI CssBaseline with React JS

Looking to enhance the consistency of my new React app with a sleek design using Material-UI. Want it to be easy to maintain, so decided to start with the default theme. Trying out cssBaseline from Material-UI but running into issues. Not very familiar wit ...

The closing tag for the "body" element was excluded even though OMITTAG NO was specified

While attempting to validate my contact support page, I encountered the following errors: Omission of end tag for "body", even though OMITTAG NO was specified ✉ You may have forgotten to close an element or intended to self-close an element by ending ...

Tips for creating a responsive background image that adjusts after resizing the window to a certain width

Is there a way to create a responsive background-image that adjusts when the window is resized to a specific width, similar to the main image on ? ...

Is there a way to automatically scroll to the bottom of a div when it first

Looking to enhance my application with a chat feature that automatically scrolls to the bottom of the chat page to display the latest messages. Utilizing VueJs: <template> <div id="app"> <div class="comments" ...

Choose data in JSON format

My attempt at selecting JSON data by its key seems to be more difficult than I expected. Below is the jQuery function I am using: $.ajax({ url: "/_add_question", data: { title: function() { return title.val(); }, ...