Understanding the usage of jQuery transitionend to prevent interruptions in CSS animations

I found a similar thread on StackOverflow but I'm struggling to apply it in my current scenario.

The Setup (Welcome Ideas)

I've developed a jQuery slider that will have multiple instances on one page, each containing an unknown number of children ('cards' displaying 4 visible cards per "slide"). The implemented code compares the container's offset, the number of children, and uses CSS transitions on the inner container to slide by the calculated offset while preventing overshooting.

I have different versions of prototypes, but I'm particularly interested in the button feature I've created.

What Works

  • Multiple sliders on a single page
  • Accurate detection of the number of "cards" within a container
  • Slide animation based on the container's offset
  • Dynamically calculating start and end values to prevent over-sliding

The Challenge

Users can spam click a button, interrupting the ongoing CSS transition (500ms) and starting a new one prematurely, causing the slider to misalign.

Possible Solution

The jQuery transitionend property appears to be the key to detecting when a CSS transition completes. However, I need assistance with its implementation.

I'm encountering difficulties understanding the technical jargon surrounding this, as explanations often lead to more complex documentation or incomplete forum responses. Any help in clarifying my mistakes and the underlying principles would be greatly appreciated.

Note

While I expect some criticism and judgment, considering my self-taught coding background with expertise limited to jQuery, courtesy and straightforward explanations supported by relevant resources are always welcomed. While the complete code is provided below, my main point of confusion lies in dealing with "transitionend," which I'm trying to incorporate using the following snippet:

$(cardsToShift).on('transitionend webkitTransitionEnd oTransitionEnd', function () {
        cardsToShift.css("margin-left", margin);
    });

In this snippet, 'cardsToShift' represents the card container that moves left/right by the pre-calculated 'margin' variable. My rationale for this code is "this container won't shift during an active transition due to the 'transitionend' line. If no transition is underway, the specified action should occur; otherwise, the user must click again" (some minor syntax issues may require cleaning up).

Thank you in advance for your assistance. I'll respond promptly upon returning online after a brief break.

HTML Code

<!-- HTML code goes here -->

CSS Styling

@charset "UTF-8";
/* CSS styles go here */

Javascript Functions

// JavaScript functions go here 

Answer №1

Alright, after a refreshing rest and some energizing coffee, I've got the answer to this query (it turned out to be more straightforward than anticipated):

Basically, transitionend event triggers once a transition has been completed on an element that is transitioning. To tackle this, I decided to set a class as a sort of "test" indicator. If the class is present, I halt any further transitions; if it's not there, then I proceed normally.

In this scenario, I can apply a CSS class to just about anything, but the key detail is utilizing transitionend with the transitioning CSS class. In the transitionend callback, I remove the originally set class so that the "disable" class is only lifted upon completing the transition, allowing the transition to execute sans the class:

/*MOVE - note that "cardsToShift" has CSS transition applied */
cardsToShift.css("margin-left", margin);

/*add class - no more movement while this is added */
$(container).addClass("disabled");

/*end of transition - disabled class removed */
$(cardsToShift).one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function() {

$(container).removeClass("disabled");

This is where the magic unfolds - you should be able to spot from my original code where exactly this snippet fits in (within my shiftCards() function).

The validation for the 'disabled class' essentially acts as a gatekeeper in the sequence like so:

/*check for the class as a gatekeeper!!! Class can only be removed once the transition completes */
if($("#"+container).hasClass("disabled"))
{
    /*do nothing*/
    console.log("DOUBLE FIRE!!!");
} else {
     /*no gatekeeper class - proceed with transition etc. */

    /*specific to the problem - ensuring there are elements to move */
    if (numOfCards > 1)
    {
        /*custom to the issue - checking if left or right button was clicked */
        if($(button).hasClass("left"))
        {
            prevCards(container);       
        } else {
            nextCards(container);
        }
    }
}

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

Are you encountering a malfunctioning AJAX Function? Seeking assistance with PHP/MySQL

I have a PHP-generated form that needs to submit data using AJAX. Here's what I have so far... PHP Form <div class="user"> <span>Start a friendship with '.$row['screen_name'].'</span> <form method="PO ...

Placement of text is incorrect on certain react cards

I have an application that retrieves videos and generates a card for each video, displaying the video title, creator, link, download option, views, and upload date on each card. Fetching and displaying these elements works well, for the most part. However ...

The JSON array object gets replaced in the local storage

I have been working on a form page where there are 3 input fields: "fname," "emailId," "phoneNo." Every time a user enters details in the form, I am storing them in localStorage. However, the object keeps getting overwritten. Here is the script: <scri ...

Adjust item size and move them into the panel

I am looking to create a panel that arranges items in a specific layout shown here: https://i.stack.imgur.com/qw3lS.png Below is the code I have attempted so far: import React, { useCallback, useEffect } from "react"; import { Box, Grid, Tab, T ...

Exploring Problems with Implementing the Jquery .click() Function on a Class

My goal is to create a simple JQuery code that triggers a pop-up message saying hello when any element of the specified class is clicked. Here's what I've tried: $(document).ready(function(){ $(".thumb_radio").click(function(){ aler ...

Transform the appearance of a complex image by altering its color using CSS

In my quest to bring a unique functionality to life, I am looking to achieve the following: I want to layer two transparent images within a <div>: one representing an object and the other depicting a glowing effect around the object. When hovering ...

Using radio buttons and setting the attribute to 'checked' does not function properly in Internet Explorer 7

Is there a way to automatically check radio buttons when appending in IE7? Despite my code working in all browsers, it seems to fail in IE6 and IE7. I can't figure out why it's not working, even though I've followed the correct steps accord ...

Scrolling horizontally to display dynamic columns based on a search query in AngularJS

I am facing a challenge with implementing search functionality in a table that has multiple dynamic columns with a horizontal scrollbar. The goal is for users to be able to search for a specific column name or data, and if a match is found, the scrollbar s ...

The "Overall Quantity" of items will vary as it goes through different numerical values, despite the fact that I employed --

I am currently working on an e-commerce website with a shopping cart feature. The cart displays the number of items added to it, which increases by one when 'Add to Cart' is clicked and decreases by one when 'Remove' is clicked. However ...

Troubleshooting a live chat box for CSS alignment issues

Need help with aligning a live chat box on every webpage? Check out this example for reference: You can find my code here: https://jsfiddle.net/fn77d0de/2/ ...

Implementing a class addition on focus event using Angular 2

Currently, I am in the process of upgrading an Angular 1 application to Angular 2 and encountering an issue with one of my existing directives. The task at hand is straightforward. When an input field is focused, a class should be added (md-input-focus) a ...

Employing JavaScript to display or conceal a <div> element while scrolling

I'm looking to create a customized sticky navigation bar through Javascript, but I have never written my own code in this language before. My approach involves implementing two sticky navigation bars that appear and disappear based on scrolling behav ...

Using the Slim framework to communicate through JSON

When attempting a simple POST request, I am having trouble reading the JSON data no matter what I try. $.ajax({ url: 'server/account/session', type: 'POST', data: { "username": name, "password": password} , ...

Locate all jQuery UI tabs individually

I'm struggling to assign a body class for one of my jQuery UI tabs when it's active Despite numerous attempts, I can't seem to make anything work. Here is my latest try: $( ".jquery-tabs" ).on( "tabsactivate", function( event, ui ) { $( ...

The CSS div mysteriously vanishes right before I can trigger the click event

My CSS code looks like this: #searchbar-wrapper input#header-searchbar:focus + #search-dropdown-wrapper { display: block; } The purpose of this code is to make a dropdown visible when a user focuses on a textbox. The default behavior should be th ...

Retrieve the identifiers of various HTML elements and store them in an array

Within a div, there are multiple objects. I am trying to retrieve the IDs of all elements based on their class, knowing that the number of elements may vary. So far, my attempt has been: arr = $(".listitem #checkBox").hasClass('checkedItem').att ...

Applying the document height to window height ratio to create a scale ranging from 1 to 100

My goal is to create a scroll bar using two divs with heights of 110px and 10px. The smaller one will be nested inside the taller one, allowing for adjustment of its margin-height from 0 to 100px while still fitting within the larger div. When I refer to ...

Switch between viewing outcomes retrieved from a database

I'm fairly new to working with jQuery, PHP and databases, but I have managed to successfully create a database and retrieve data using PHP. When a search term is entered, the retrieved data from the database is displayed on the results page. For exam ...

Shifting the div with a sliding animation!

My webpage features a video background with text overlay, and I am looking to add a button in the center of the page. When users click on this button, I want the current text div to slide up using a CSS transition, revealing another div with the same effec ...

The table populated by Ajax is blank

I am facing an issue while trying to display a table using AJAX and PHP. The table is not appearing in the designated div. Since I am new to AJAX, I have limited knowledge about its functionalities. Below is the HTML code for my div: <div class="body" ...