Doesn't the .stop(true) function completely clear the queue as it should?

My slideshow has a hover function to pause it using .stop(true). Upon mouse exit, it should resume playing from where it left off. However, currently, when I hover over it, the animation stops and then continues until it reaches its target, pausing there as if waiting for the animation to complete. I'm unsure of what's causing this behavior.

Html:

<section class="photo-grid-slideshow">
    <div class="photo-crop">
        <h3>I wanna
            <div class="xs-spacer"></div>
            <a class="med-btn btn-white">Read more</a>
        </h3>
        <div class="photo-grid-container" style="background-image: url('Images and videos/odesza1.jpg');"></div>
    </div>
    <div class="photo-crop">
        <h3>Dance
            <div class="xs-spacer"></div>
            <a class="med-btn btn-white">Read more</a>
        </h3>
        <div class="photo-grid-container" style="background-image: url('Images and videos/odesza3.jpg');"></div>
    </div>
    <div class="photo-crop">
        <h3>With you
            <div class="xs-spacer"></div>
            <a class="med-btn btn-white">Read more</a>
        </h3>
        <div class="photo-grid-container" style="background-image: url('Images and videos/odesza2.png');"></div>
    </div>
            <div class="photo-crop">
        <h3>With you
            <div class="xs-spacer"></div>
            <a class="med-btn btn-white">Read more</a>
        </h3>
        <div class="photo-grid-container" style="background-image: url('Images and videos/odesza4.jpg');"></div>
    </div>
</section>

Css:

.photo-crop {
    display: inline-block;
    overflow: hidden;
    float: left;
    width: calc(100vw / 3);
    height: 100%;
    padding: 0;
    position: relative;
    background-position: center center;
    background-size: cover;
    text-align: left;
}

.photo-grid-slideshow {
    height: 300px;
    display: inline-block;
    min-width: 300%;
    position: relative;
    background: black;
    padding: none;
    overflow: hidden;
    background: #444;
    margin-left: 0;
    left: 0;
}

Script:

$(function(){
  function animate(){
      var p = $(".photo-grid-slideshow .photo-crop").css('width');
      $(".photo-grid-slideshow .photo-crop:first-of-type").animate({marginLeft: '-=' + p}, 10000, "linear", function(){
        $(this).css("margin-left", 0).appendTo('.photo-grid-slideshow');
        animate(); // here we call it again
    })
  }
  animate(); // start animation
})

$(".photo-grid-slideshow").mouseenter(function() {
    $(".photo-grid-slideshow .photo-crop:first-of-type").stop().clearQueue();
})

$(".photo-grid-slideshow").mouseleave(function() {
    $(function(){
        function animate(){
            var p = $(".photo-grid-slideshow .photo-crop").css('width');
            $(".photo-grid-slideshow .photo-crop:first-of-type").animate({marginLeft: '-=' + p}, 10000, "linear", function(){
            $(this).css("margin-left", 0).appendTo('.photo-grid-slideshow');
            animate(); // here we call it again
        })
    }
        animate(); // start animation
    })
})

Answer №1

This situation presents an intriguing challenge. The primary issue lies in failing to cache the current margin-left of the initial element, resulting in a brief delay. As the initial elements animate, their movements continue even when they are no longer within the photo-grid-slideshow container. This means that upon hovering over the slideshow, the animations pause momentarily. For instance, if the margin-left is stopped at -55px and the image width is 200px, upon restarting the animation, the width is calculated based on the previous margin-left setting, leading to a wider element (255px). This discrepancy causes interruptions in the animation flow, as the first element must complete its movement of 255px before allowing the next element's animation to begin.

// Obtain the width of the initial element only once
var widthEl = parseInt($(".photo-crop").first().css('width'));
// Create an auxiliary variable to store the margin-left value
var aux = 0;
// Separate the animation function for clarity
function animate(p){
    // Select the initial element
    $(".photo-crop").
        first().
        animate({marginLeft: '-=' + p}, 5000, "linear", function(){
            $(this).css("margin-left", 0).appendTo('.photo-grid-slideshow');
            // Pass the current margin-left value
            animate(p); // recursion 
        });
};
// Chain event listeners using chainnable option
$(".photo-grid-slideshow").mouseenter(function() {
    // Calculate the margin-left of the initial element to pause the animation
    aux = widthEl - parseInt($(".photo-crop").first().stop().css("marginLeft")) * -1;
}).mouseleave(function() {
    // Resume animation by passing the current margin-left value
    animate(aux);
});
// Start the animation with the initial element width
animate(widthEl); 

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

Error: JSON parsing failed due to an unexpected token 's' at position 1

I am currently developing a plugin and facing an issue with updating post meta in Wordpress. I have created a PHP code to handle this task by receiving an array/object/json array: public static function save_settings_fields(){ $myArray = json_decode( ...

Executing Code from Tab only upon tab activation

I have multiple tabs on my page, and I want to have one tab with a widget that only loads when the user clicks on it, instead of loading along with all other tabs when the page loads. <div class="tabbable tabbable-custom"> <ul class="nav nav-t ...

Switch up the Javascript popup code without any specific pattern

I am looking to add variety to my pop up ads on my website by randomly changing the Javascript code for each ad every time a page is loaded. How can I achieve this? Script 1 <script type="text/javascript"> var uid = '12946'; var w ...

Is there a way to incorporate a text box in javascript that displays the retrieved reference count from the database?

I'm currently working on creating a functionality that retrieves rows with the same ID from a database and displays them in a text box. Below is the PHP code I've written for retrieving all the rows: PHP: <?php include_once('pConfig ...

Improve the looping mechanism to efficiently extract key values from an object and store them in an array

I am working with an object that contains various questions, each with a different difficulty level indicated by the "difficulty" property. I have implemented a for loop to sort the questions into categories based on their relative difficulty, such as easy ...

When a nested CSS Grid is inserted into an HTML table element, it causes horizontal overflow

     Generating an invoice dynamically with a CSS grid poses some challenges. To maintain a specific format, I need to define the number of rows and columns in advance along with column widths. Using template rows and columns for this purpose restrict ...

AngularJS OAuth authentication Pop-up: Waiting for JSON response

I am looking to initiate an oauth request in a new window for my project. Here is how I can open the new window: var authWindow = $window.open("/auth/google/signin", ""); After the callback, my server will respond with JSON data: app.get('/auth/ ...

When utilizing Vue components, the issue of "setattr" arises when trying to assign

Having recently started using Vue.js, I encountered an issue while trying to implement components. Interestingly, the code worked perfectly fine before implementing components. I'm facing an error that is proving to be quite challenging to understand ...

You can activate the ability to click on the main tag by setting routerlink as the child component in Vue

Within my HTML code, I have utilized a RouterLink within an li tag to create a basic dropdown menu. Currently, when options are displayed in the dropdown menu, I am only able to click on the text itself to navigate to the next page. However, I would like t ...

display the text from the template after selecting it (including both the text-field and value-field)

I'm currently utilizing BootstrapVue. In my b-form-select component, I display the name (as the text field) in the selection within my child.vue and emit the age (as the value field) to my parent.vue. This functionality is functioning as intended. H ...

Can MUI FormControl and TextField automatically validate errors and block submission?

Are MUI components FormControl and TextField responsible for error handling, such as preventing a form from being submitted if a required TextField is empty? It appears that I may need to handle this functionality myself, but I would like some clarificatio ...

Design your website with CSS by incorporating hanging ::before labels that feature unique formatting

I am looking to create labels that designate specific groups of words. Here are the criteria: The label should appear to the left of the word group The words should be enclosed in lines, while the label should not The words should be indented, while the ...

ReactJS - When a child component's onClick event triggers a parent method, the scope of the parent method may not behave as anticipated

In my current setup, I have a parent component and a child component. The parent component contains a method within its class that needs to be triggered when the child component is clicked. This particular method is responsible for updating the store. Howe ...

Sorting a table using jQuery

I'm working with this table structure: <table> <th> Food Name </th> <th> Restaurant Name </th> <?php if ($isCustomer == "1") { ?> <th> </th ...

Updating the unordered list (UL) of rows in MySQL dynamically

Currently working on a test site that aims to function as a video playlist player pulling videos from the VIMEO API based on URL numbers (like vimeo.com/7100569) The setup involves storing a list of these URLs in a MySQL table. At this stage, I have manag ...

What is the reason for having a space between the <body> and the <html> tags?

Can you explain why there is a gap between the top of the green box and the browser window in Chrome and Firefox? I've tried various CSS configurations to eliminate the apparent space between the html and body elements, but it seems that some padding ...

Can you import folders containing *.vue files in your project?

Repeating code is my least favorite thing. Currently, I am importing vue files in a repetitive manner in my main.js file. import Default from '../../src/components/default.vue'; import Home from '../../src/components/home.vue&apo ...

Exploring the world of color in Google visualization charts

I am currently working on a project that requires me to add different colors to specific zones on a graph. I am looking to use colors such as blue, red, yellow, and green. Here is the outcome I have achieved: I am aiming for something similar to this des ...

Does shouldComponentUpdate returning `true` have the same effect as not having shouldComponentUpdate at all?

Within my React Native component, I have included a blank shouldComponentUpdate shouldComponentUpdate(nextProps, nextState) { } I am aware, from reading this answer, that an empty shouldComponentUpdate function helps in eliminating unnecessary re ...

AngularJS - one-time execution of view generation from .NET controller

Currently, I have an MVC .NET application integrated with AngularJS. In my route provider configuration, I am utilizing the controllers of MVC to retrieve the views as shown below: .when('/Units', { templateUrl: 'Unit/Units' ...