Using jQuery to show/hide linked CSS3 animations upon Mouseenter/Mouseleave events

Exploring the capabilities of animate.css and jQuery within a bootstrap environment has been quite interesting for me. However, I've encountered a major issue!

I am attempting to trigger animations on mouseenter / mouseleave, which led me to create a series of complex chained callbacks that are now causing me frustration.

Take a look at my jQuery code (using no-conflict mode due to other plugins):

jQuery(document).ready(function () {

    var animationend = "webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend";
    var imgRotacion = "animated rotateOut";
    var h3Bounce = "animated bounceIn";
    var pFlip = "animated flipInX";
    var imgRotacionOff = "animated rotateIn";
    var h3BounceOff = "animated bounceOut";
    var pFlipOff = "animated flipOutX";


    jQuery(".procaption").on("mouseenter", function () {

        jQuery(this).find("img").addClass(imgRotacion).one(animationend, function () {
            jQuery(this).hide();
            jQuery(this).parent().find("h3").removeClass("hidden").addClass(h3Bounce).one(animationend, function () {
                jQuery(this).parent().find("p").removeClass("hidden").addClass(pFlip);
            });
        });
    });


    jQuery(".procaption").on("mouseleave", function () {
        jQuery(this).find("p").removeClass().addClass(pFlipOff).one(animationend, function () {
            jQuery(this).removeClass().addClass("hidden");
            jQuery(this).parent().find("h3").removeClass().addClass(h3BounceOff).one(animationend, function () {
                jQuery(this).removeClass().addClass("hidden");
                jQuery(this).parent().find("img").removeClass(imgRotacion).show().addClass(imgRotacionOff);
            });
        });
    });


});

The HTML structure is fairly simple:

<div class="procaption wow fadeInLeft well text-center">
      <img src="holder.js/150x150" alt="150x150" class="img-responsive img-circle center-block">

      <h3 class="hidden">This is a title</h3>

      <p class="hidden">But this is a description!</p>
</div>

The desired behavior: My goal is to sequence all the animations so they appear and disappear in a specific order upon mouseenter and mouseleave events.

Currently, it seems to be "working", but only when the mouseleave event is triggered after the last animation of the mouseenter event has completed.

When I attempt to quickly do a mouseenter followed by a mouseleave, the

<p>But this is a description!</p>
line appears simultaneously with the <img>... This should not occur!

Here's the link to the jsFiddle.

I believe there must be a simpler solution, but as I'm still learning and practicing, any guidance or suggestions would be greatly appreciated!

Just to mention, I attempted changing the .procaption class to .procaptioning during the animation until the final callback completes, but it didn't work :( I also tried using

$(".procaptioning").on("mouseenter mouseleave", function() { return false; })
... without success.

Answer №1

Your usage of .removeClass() is causing issues as it is not targeting specific elements. This can lead to unexpected results when quickly hovering on and off, as overlapping functions may interfere without clear instructions on which classes to remove at each step. I have simplified the code by minimizing nested this references and ensuring consistent selectors are used. You can view a working example in this FIDDLE.

function onHoverIn(e) {
    var $caption = jQuery(this),
        $image = $caption.find('img'),
        $h3 = $caption.find('h3'),
        $desc = $caption.find('p');

    $image.addClass(imgRotacion).one(animationend, function () {
        $image.addClass('hidden');
        $h3.removeClass('hidden').addClass(h3Bounce).one(animationend, function () {
            $desc.removeClass(pFlipOff + ' hidden').addClass(pFlip);
        });
    });
}

function onHoverOut(e) {
    var $caption = jQuery(this),
        $image = $caption.find('img'),
        $h3 = $caption.find('h3'),
        $desc = $caption.find('p');

    $desc.removeClass(pFlip).addClass(pFlipOff).one(animationend, function () {
        $desc.removeClass(pFlipOff).addClass('hidden');
        $h3.removeClass(h3Bounce).addClass(h3BounceOff).one(animationend, function () {
            $h3.removeClass(h3BounceOff).addClass('hidden');
            $image.removeClass(imgRotacion).removeClass('hidden').addClass(imgRotacionOff);
        });
    });
}

jQuery(".procaption").hover(onHoverIn, onHoverOut);

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

Nested data selection in React

I have been experimenting with creating a nested select optgroup and attempted the following: const data = [ { sectorId: 5, sectorName: "Sector One", departments: [ { deptName: "Production", jobtitles: [ { ...

Using JavaScript variables in a Jinja array

I encountered a frustrating issue that has been causing me some trouble. In my project setup, data is being transferred from Python to the frontend using Jinja in the form of a 2D list. My goal is to loop through this array using a for loop, but I'm ...

Implementing a delay between two div elements using jQuery

I have two Divs with the class "sliced", each containing three images with the class "tile". When I animate using jQuery, I am unable to add a delay between the "sliced" classes. However, I have successfully added a delay between the "tile" classes. index ...

Discover the technique of accessing HTML/CSS toggle switch value in Golang

I am attempting to incorporate a toggle switch into my webpage. I followed this specific tutorial for guidance: w3schools.com Currently, I have set up my HTML file with a button and the toggle switch. Additionally, I configured my web server in Go to lis ...

JQuery UI button causing an error in Internet Explorer related to "potentially harmful Request.Form value"

While testing my application with Internet Explorer, I discovered that buttons styled with JQuery UI button are sending their entire content to the server. This causes a "A potentially dangerous Request.Form value was detected from the client" error in ASP ...

Instructions for including a script and stylesheet exclusively on a single page of a website

I need to incorporate these two lines onto a single page of my website: <script src="//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.js"></script> As well as <link href="//cdnjs.cloudflare.com/ajax/libs/OwlCa ...

What is the best way to center the 'email promo' text in the top navigation bar alongside the image and other text links?

Struggling with learning CSS and HTML, particularly when it comes to positioning elements on the page. I'm having trouble vertically aligning the elements inside the top nav bar and can't seem to figure out what I'm doing wrong. Any insights ...

Experiencing browser crashes following the incorporation of asynchronous functions into a JavaScript file. Seeking solutions to resolve this

In my recent project, I developed a basic online store application using vanilla javascript and ES6 classes. The shop items are stored in a JSON file which I used to populate the user interface. To implement functions like "addToCart", "quantityChange", a ...

Manipulating CSS Class Properties Using JavaScript

In my JavaScript application, there is a functionality that loads a list of items for users to click and view detailed information in a separate div on the page. Users should be able to interact with and make modifications to these individual item overview ...

Enhancing jQuery AJAX Performance with Promises and Deferred Objects for Seamless Callback Management

Consider this scenario: Checking the stock availability of a product multiple times in an ecommerce-script. Initially, I implemented it as follows: var checkStock = function(id) { $.ajax({ type: "POST", dataType:'json', url: "class ...

Setting up only two input fields side by side in an Angular Form

I'm fairly new to Angular development and currently working on creating a registration form. I need the form to have two columns in a row, with fields like Firstname and Lastname in one row, followed by Phone, Email, Password, and Confirm Password in ...

Placeholder variable not specified in radio buttons

I am currently facing challenges applying validations to radio buttons in Angular. Normally, I create a #templateRefVariable on the input for other input types, which allows me to access the NgControl and use properties like touched. My goal is to set the ...

Tips for accessing a website and logging in to extract important data for scraping purposes

Currently facing an issue with scraping data from a website that requires logging in. I've been attempting to use the node request package for the login process, but so far have been unsuccessful. The code snippet I'm currently using is: var j = ...

What is the best way to connect my Angular 2 project to the "$wakanda" service in order to access and retrieve data efficiently?

Recently, I started a new project on the wakanda.io platform using angular2 and backend technologies. After creating some database entities, I now need to retrieve data from the database on the client side. To do this, I am looking for a way to import the ...

The 'v-model' directive necessitates a valid attribute value for the left-hand side (LHS)

I am facing an issue with my Vue application. I have a table where each row has its own unique id. I need to show or hide certain elements based on a condition in the v-model directive which compares the row id with a value in the model. The current code s ...

Determine the vertical dimension of a child division once it has been integrated into an HTML document

My goal is to create a website with multiple pages without having to recreate the toolbar for each page. To achieve this, I have created a separate HTML file and CSS file specifically for the toolbar. On each page, I simply import the toolbar using the fo ...

Generating numerous circular elements for each item in the dataset using D3

My dataset consists of various years and corresponding numerical values for each year as shown below: "data":[ ["1951","306","27","159","34","82","4"], ["1956","426","41","203","47","119","16"], ["1959","562","67"," ...

Understanding Arrays in Angular JSIn this article, we

I am new to working with Angular JS. Currently, I am populating an array and attempting to showcase its contents on the HTML page using ng-repeat. $scope.groupedMedia = []; // Elements are being added through a for loop. $scope.groupedMedia[year].push(r ...

Displaying decimal values in Angular as percentages

In my Angular application, I have a numeric textbox that displays a percentage value and allows users to update it. https://i.stack.imgur.com/eCOKe.png <label for="fees">Fees %</label> <div class="inpu ...

Set the value of a static file uploader using jQuery

I am having trouble retrieving the name of an existing file in a file uploader. I have a sample in jsfiddle demonstrating what I have tried. http://jsfiddle.net/shree/a4PKG/3/ However, when I click GetImage, the file uploader always remains empty. T ...