"Creating Eye-Catching CSS Animation Effects with Dynamic Initial States

I am looking to understand how I can seamlessly transition from a hover-triggered animation to an exit-hover animation, regardless of where the hover animation is in progress. Currently, if I exit hover too quickly, the animation jumps back to its starting position.

Is there a way to ensure that even if I exit hover prematurely, the animation will complete before transitioning into the exit-hover animation?

If you click here, you can see a live demo of what I'm trying to achieve.

Here's a snippet of my HTML and CSS:

<div class="image-container">
        <img src="https://dummyimage.com/200x200/000/fff">
</div>

.image-container {
  margin: 50px;
}
img {
  width: 100px;
  -webkit-transform: rotate(-45deg);
}
img.over {
  -webkit-animation: enlarge .5s cubic-bezier(.42,0,.8,1) both,
         enlarge-2 .25s cubic-bezier(.2,0,.3,1) .5s forwards;
}
img.out {
  -webkit-animation-name: shrink;
  -webkit-animation-duration: .5s;
  -webkit-animation-timing-function: ease-in-out;
  -webkit-animation-iteration-count: 1;
  -webkit-animation-fill-mode: both;
  -webkit-animation-direction: forwards;
}
@-webkit-keyframes enlarge {
  from {transform: rotate(-45deg) scale(1);}
  to {transform: rotate(0deg) scale(1.5);}
}
@-webkit-keyframes enlarge-2 {
  from {transform: scale(1.5);}
  to {transform: scale(1.3);}
}
@-webkit-keyframes shrink {
  from {transform: rotate(0deg) scale(1.3);}
  to {transform: rotate(-45deg) scale(1);}
}

And here's the JavaScript implementation:

$("img").hover(
    function () {
        $(this).removeClass('out').addClass('over');
    },
    function () {
        $(this).removeClass('over').addClass('out');
    }
);

Answer №1

The following code snippet has not been tested, but it demonstrates the concept of implementing a semaphore to schedule a timeout for releasing the semaphore at the end of an animation.

function handleHoverAnimation(context, intervalLength) {
    var isRunning = false;
    var currentEvent = undefined;
    var scheduledAction = undefined;
    
    function executeEvent(currentContext, event) {
        if (isRunning) {
            if (currentEvent !== event) {
                scheduledAction = event;
            }
        } else {
            isRunning = true;
            currentEvent = event;
            event(currentContext);
            setTimeout(function() {
                currentEvent = undefined;
                isRunning = false;
            }, intervalLength);
        }
    }
    
    function hoverEffect(currentContext) {
        currentContext.removeClass("out").addClass("hover");
    }
    
    function unHoverEffect(currentContext) {
        currentContext.removeClass("hover").addClass("out");
    }
    
    context.hover(function() {
        executeEvent($(this), hoverEffect);
    }, function() {
        executeEvent($(this), unHoverEffect);
    });
}

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

Guide on displaying a grid in the center of the screen with a vertical sliding feature

I've noticed certain apps displaying a grid view or form on an alert box with vertical sliding, but I'm clueless about how to make it happen. As far as I know, this can be achieved using jQuery.. Any assistance would be greatly appreciated. Th ...

When zooming in or out on a mobile device, an unusual white line appears

Encountering a strange white gap on mobile devices when zooming in or out. This issue seems to be related to the use of background-color on sections. Strangely, the problem only occurs on mobile devices while zooming in, but does not appear on normal deskt ...

Calculate the sum of floating point or decimal numbers from a textarea using JavaScript

I'm trying to work with a text area that contains decimal/float numbers. However, the code I found online seems to be ignoring commas and periods when summing up the values. Is there a way to handle decimal/float numbers correctly in this scenario? ...

Is there a more efficient method for handling this JSON dataset?

After delving into Sitepoint's "Novice to Ninja" and starting to explore jQuery, I can't help but question if there is a more efficient way to write the code I've put together. The resounding answer appears to be "yes." All these cumbersome ...

Tips for detecting a false return value from a jQuery AJAX script

I am currently utilizing jQuery and AJAX to perform form validation when a new user is being created on my website. My development environment consists of OOP PHP in conjunction with jQuery and AJAX. Here is the code snippet I am using: $.ajax({ ...

Unable to find '.file.scss' in the directory '../pages'

I am currently in the process of migrating my Ionic 3 app to version 4. However, I have encountered an issue where some pages are not recognizing the SCSS file from the TypeScript component. @Component({ selector: 'car-id', templateUrl: &apo ...

Tips for containing content within a div element

Does anyone know how to achieve this using CSS? https://i.sstatic.net/1eY38.png I'm having trouble keeping the written content inside the wrapper div, like this: https://i.sstatic.net/5vDot.png I attempted to use material-ui Grid but didn't h ...

Adjust the dimensions of the bootstrap dropdown to match the dimensions of its textbox

The second textbox features a bootstrap dropdown with extensive content that is overflowing and extending to other textboxes below it. I am looking for a way to resize the dropdown to fit the size of its corresponding textbox. UPDATE: I want the dropdown ...

Problem with Flexbox Wrapping on iPhone 6

I love the flexibility that flexbox provides, but I've been facing an issue specifically with wrapping on iOS devices. Is there a simple fallback option for handling wrapping? Here's a problem scenario where items refuse to wrap: ( JSFiddle Fans ...

How can I align the title of a cell to the left while centering the remaining content?

I have a dilemma with two table cells placed side by side that stack upon triggering a media query for an HTML newsletter. I wish to align the headlines "Be Ready" and "Stay Organized" to the left when the responsive code activates, but the use of "margin: ...

Tips for Changing Background Color Beyond Body Tag

When using my demo below on Safari for iOS and scrolling up and down, you'll notice that you can scroll outside of the body until removing your finger from the touchscreen. The background color outside of the body is white. Is there a way to change th ...

What methods can I use to identify the selector for this element?

After pinpointing the specific element in Google Chrome using inspect element, what kind of path or syntax should I use to apply a method to this element? The hierarchy for the element is outlined below: html body div#contentDiv div#searchFormDiv ...

Tips on increasing the button size automatically as the elements inside the button grow in size

I have a button with an image and text inside, styled using CSS properties to achieve a specific look. However, I encountered an issue where the text overflows outside of the button when it's too long. I want to find a way to wrap the text inside the ...

The box-shadow feature seems to be disabled or ineffective when trying to send HTML content via

I am having a unique approach to sending emails using html. To combat the issue of image blocking by email providers, I have resorted to utilizing box-shadow to create the images I require. The strange thing is that it appears perfectly fine in the browser ...

What is the best way to populate checkboxes using an Ajax request for the RelatedUserAccessPermission function in a Razor Page MVC?

In my work on .NET core 7 MVC razor page, I'm encountering an issue where I am unable to fill the checkboxes with the IDs StockTake and ShelfLabelPrint using an AJAX request to the function RelatedUserAccessPermission.</p> <p>Below is the ...

I'm stumped trying to understand why I keep getting this syntax error. Any thoughts on how to fix it?

Our team is currently working on creating a dynamic SELECT box with autocomplete functionality, inspired by the Standard Select found at this link: We encountered an issue where the SELECT box was not populating as expected. After further investigation, ...

JSON structure in a loop

I'm facing an issue with looping through my JSON data. Although I am only looping through "id_first", after printing 1 and 2 correctly, it then moves on to "id_second" and prints undefined. How can I make sure that my loop only prints id first? Here ...

Showing exclusively JavaScript data in a select element

I am struggling with getting a select tag to display only JavaScript values. Here is the code snippet: <select id="pname"> <option>som data</option> </select> After running a JavaScript function, I want to update the select ta ...

Attach a sticker to the input field

I want to position a label on top of an input tag permanently, rather than having it inside the input tag where it jumps to the top when clicked. Here is my attempted solution: input { font-size: 18px; padding: 10px 10px 10px 5px; -webkit-appeara ...

Using JavaScript to add a class when hovering over an element

I am trying to customize the ul inside one of my li elements in the nav by adding a class when hovered. However, I am encountering an issue where the menu disappears when I try to click on it after hovering over it. I want to achieve this functionality usi ...