"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

Incorporate text inside the border of a Material UI chip

https://i.stack.imgur.com/VATrD.png I'm looking to replicate this design using a pre-built Chip component from MaterialUI While the solution might involve Some Text using html and css, it still may not achieve an identical result. I've come acr ...

The unexpected blank space appearing beneath my website as a result of images and videos placed on the

There seems to be some random white space on my website between the main body elements and the footer. Interestingly, removing the cat image and videoplayer eliminates this white space. However, I don't want to remove them completely, so I'm tryi ...

Appium successfully triggers a click action on an obscured WebElement

I am facing an issue with my android appium test for an android application. The app contains a webview with a loader that appears at the start. There is a link within the app that I need to click on, which should navigate to another web-page. Although ...

What is the best way to automatically create a line break once the User Input reaches the end of a Textbox?

I've been searching for a solution to this question without any luck. Here is the tag I'm working with: <input type="text" id="userText" class="userTextBox"> And here is my CSS: .userTextBox { /* Add marg ...

Troubleshooting CSS Display Problem on Chrome and Firefox

While working on the design of a website offline, everything seemed to be running smoothly. However, upon uploading it to the server, various issues began to arise. Initially, the file loaded correctly upon first visit. Unfortunately, after reloading the ...

The design breaks occur exclusively in the Android default browser

I am experiencing issues with the design of a nested div element when viewed in the default Android browser. Unfortunately, I don't have access to tools that would allow me to identify the cause of this problem. However, the design functions correctly ...

Assistance needed in obtaining the ID of a specific table row using jQuery

Currently, I am working on an AJAX request using Jquery and PHP. The task involves looping through an array to generate a table. During each iteration, a new ID is assigned to the table row. When users click on the "read me" link, additional content is f ...

What is the best way to conceal a dynamically-loaded element on a webpage?

I wrote a script that utilizes AJAX to fetch data from a PHP file named names.php. Later in the script, I used jQuery's $(document.ready(function(){}); to attempt hiding a div when the DOM is loaded. Strangely, the $("div").hide() function isn' ...

Tips for preserving the contents of a list with HTML and Javascript

My latest project involves creating a website with a To-Do list feature. Users should be able to add and delete items from the list, which I achieved using JavaScript. Now, my next goal is to ensure that the current items on the list are saved when the pag ...

Issue encountered during an asynchronous call to an ASP.NET web method using $Ajax

Currently, I am dealing with an async web method (asmx file) and I am trying to call this method within an ajax jquery method. However, I am encountering numerous issues because the method also utilizes Entity Framework for various functionalities. Below ...

Unique ideas for organizing the layout and loading of content on my website

Last year, I created a fan site dedicated to a popular PC game, but now I feel like it could use some improvements. Currently, all the pages on my site share a common header and footer, with only the main content area changing from page to page. My curren ...

How to perfectly align an element within a div using Bootstrap

Utilizing bootstrap here. Currently trying to center the h1 element within the div, but so far I have been unsuccessful. It consistently remains aligned to the left. Attempts have included using bootstrap's center-block helper class, as well as the fl ...

Updating a section of a webpage using jQuery Mobile

I'm currently facing an issue with modifying a specific section of my webpage. Although this problem has been discussed before, I haven't found a satisfactory solution yet. The element in red on the page needs to change dynamically based on the ...

Differentiate input elements with custom styling

I'm experiencing an issue while trying to style a specific form field in Angular 7. The style doesn't seem to be applying properly. Below is my form structure: <ul> <li> <mat-form-field *ngIf="number"> <input ma ...

When implementing Critical CSS, the Jquery function fails to execute upon loading

Currently, I am working on optimizing my website at . In an attempt to improve its performance, I decided to implement critical CSS using penthouse. The Critical CSS code can be found here, generously provided by the main developer of penthouse. However, ...

Adding an <a> tag within an <li> element can lead to complications

I'm having trouble inserting an anchor tag into a list item. I can't figure out why it's not working. navListItem = '<li class="p-list-item"></li>'; mainLink = '<a class="main-a" href="' + ...

The use of jQuery's ajax() function to retrieve JSON data from a URL is resulting in a response that is

I am facing an issue where the data object received in my complete() callback is not a JSON object, but rather an [Object object]. Despite this, I can still see a string of my JSON response in data.responseText. Below is my jQuery .ajax request: $.ajax({ ...

Extracting Parameters using JQuery's load Method

On a webpage, I am attempting to load a jsp page (another.jsp) within a div element while passing parameters. $("#div").load('another.jsp?a=1&b=2'); Despite trying various methods multiple times, I have not been able to get the desired outc ...

What is the best way to ensure the right six-column DIV remains at the top in responsive web design?

I have implemented a custom 12-column grid and have created a row structure as follows: <div class="row"> <div id="the-pink" class="lg-6 md-12 sm-12"><!-- content --></div> <div id="the-violet" class="lg-6 md-12 sm-12"&g ...

transitioning from having async set to false to now setting it to true

Hey there! I'm currently facing an issue with a piece of code that needs some tweaking. The code snippet below is meant to load JSON files asynchronously, but I need it to work in sync with jQuerymobile for better functionality: var Loader = { b ...