Optimizing jQuery hover animations

I've managed to get my hover effect working, but I'm looking for ways to optimize it as there seems to be some lag when the script is searching for the .overlay div. I also made the mistake of animating all .overlay divs on the page, which I now realize was a beginner error.

So, let's explore how we can improve the code below!

jQuery:

// fetch aside feature
var aside_feature = $('aside .feature');

// fade it in on hover
$( aside_feature ).hover(function() {
    // find the overlay div
    var feature_overlay = $(this).find('.overlay');
    $(feature_overlay).stop().fadeIn();
// fade it out on hover out
}, function() {
    $(this).find('.overlay').stop().fadeOut();
});

Markup:

<aside>
    <div class="feature">
        <div class="overlay">
            <a href="">button</a>
        </div><!-- overlay -->                                          
        <div class="text">
            <p>text</p>
        </div><!-- .text-->
        <div class="image">
            <figure>
                <img src="" alt="">
            </figure>
        </div><!-- .image -->
    </div><!-- .feature -->
</aside><!-- aside -->

Fiddle: http://jsfiddle.net/9xRML/5/

Edit - Final Code

Many thanks to @Shomz and @Afro.

After considering various options, I decided to incorporate transitions, along with utilizing modernizr for detecting CSS transition support detection for transitions. I changed the hidden overlay div to have opacity: 0; *display:none; and used JavaScript as a fallback:

CSS

.overlay {
   *display: none;
   opacity: 0; 
   transition: 0.4s all linear;
}
.overlay:hover {
   opacity: 1;
}

jQuery

$(function () {
    /*=====================================
    =           Feature overlay           =
    =====================================*/
    if (!Modernizr.csstransitions) {
        // get aside feature
        var aside_feature = $('aside .feature');

        // on hover, fade it in
        $( aside_feature ).hover(function() {
            $(this).find('.overlay').stop(true, true).fadeIn();
        // on hover out, fade it out
        }, function() {
            $(this).find('.overlay').stop(true, true).fadeOut();
        });
    }
});

Answer №1

If you're aiming for optimal performance, consider switching to CSS animations. A simple way to achieve this is by setting the default opacity of the overlay to 0 (instead of using display: none;) and triggering it to appear on .feature:hover. Don't forget to add the transition property like so:

// applies a 4ms transition to any possible property with no easing
transition: all .4s linear;

Check out the complete example here: http://jsfiddle.net/9xRML/6/

For more insights on the performance disparity between CSS and JS animations, take a look at this informative article: (and there are plenty more available)

Answer №2

After some investigation, I believe I have found a solution to your problem by making slight modifications to the existing HTML code:

Utilizing JQuery

$('aside .feature').hover(function() {
    $(this).find('.overlay').stop(true, true).fadeIn();
}, function() {
    $(this).find('.overlay').stop(true, true).fadeOut();
});

Adjusting the CSS

.feature {
    background: #ccc;
}
.overlay {
    display: none;
}

This adjustment ensures that the overlay element is only visible when hovered over.

For more information on .stop(), please refer to this link.

The use of .stop(true, true)

By incorporating .stop(true, true), we can achieve a smooth fade effect while avoiding the issue of multiple queued animations.

View the DEMO

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

Achieve equal heights and vertical alignment for Bootstrap 4 accordion header with floated left and right divs

Building a Bootstrap 4 accordion, I encountered an issue. In the button header, I have two divs with one floating left and the other floating right. The right div contains an image, while the left div contains a title and a subtitle. Everything works perf ...

Tips for adding an asterisk to the label of a Material-UI switch component

I am trying to include an asterisk symbol in the label by passing a required prop with a property, but it doesn't seem to be functioning correctly. <FormControlLabel control={ <Switch onChange={event => ...

The layout of HTML emails appears to be malfunctioning on Outlook

Having trouble with my HTML email format not displaying properly in Outlook. The code includes Angular and Bootstrap CSS. I've even added inline CSS specifically for Outlook, but the table stretches to full screen when viewed in Outlook. I've tr ...

Create a DIV element that completely fills the vertical space available

My webpage is currently looking quite empty, with only one DIV element present: <div style="height: 20%; min-height: 10px; max-height: 100px; width: 100%; background-color: blue;"></div> I' ...

Generating a list of objects from an array of strings

I am currently facing an issue in my code and I could use some help with it. Below are the details: I have a array of string values containing MAC addresses and constant min & max values. My goal is to map over these MAC values and create an array of obje ...

How to retrieve input value without the need to click a button or submit the form in PHP

I have an HTML code that includes a hidden input storing a value. I need to retrieve this value and assign it to a PHP variable without requiring any user interaction such as clicking a button. The intended purpose is to use this value for obtaining data f ...

Create an animation effect on HTML tab content to slide in and out smoothly, resembling a carousel, using

I am new to animation and looking for help with creating a carousel effect on my HTML tabs using CSS. I want the contents to slide like in this example: . Any guidance or tips on how to achieve this would be greatly appreciated. <div class="service-tab ...

Arranging all text boxes in a horizontal line: A simple guide

Is there a way to align all text boxes in a single row that works properly in both IE and Chrome browsers? IE 11 display: https://i.sstatic.net/wGITo.png Chrome display: https://i.sstatic.net/jXs0r.png Textboxes are not aligned properly as shown below: ...

Trying out a directive with the use of .$on

I have created a few controllers using the .$on method and have successfully tested them. You can view an example on Plunker: http://plnkr.co/edit/8cwcdPc26PVAURmVFR8t?p=preview Currently, I am working on a directive that also uses the .$on method in its ...

Switching off toggle does not switch back to primary theme when clicking again for the second time

When I click the button for the first time, it changes the theme. However, when I click it a second time, nothing happens; it seems like it's stuck on the second theme forever. It should change themes with every click. Can someone please help me with ...

What is the best way to save a key and its corresponding value into an array storage?

Storing input data in an object with key-value pairs like so: const object1 = { un: inp.value, pw: inpw.value }; var myJSON = JSON.stringify(object1); var myObj = JSON.parse(myJSON); Now, I aim to store each object in an array. For example, the f ...

Improving efficiency for handling a vast number of inputs in React applications

Dealing specifically with Material UI, I am faced with the challenge of rendering a large number of inputs (more than 100) while effectively managing global state. Performance issues arise when using the Material UI <TextField /> component, with noti ...

What steps can be taken to ensure a neutral value is returned in Mongodb aggregation when the specified attribute does not exist?

I need to create an aggregation that looks like this: Game.aggregate([{ $match: { "_id": { "$in": result.games } } ...

Enhance Your Form Validation with jQuery UI Dialog Plugin

Currently, I am utilizing the bassistance validation plugin for form validation. I have set up a pop-up modal dialog box to contain a form that requires validation, but for some reason, the form is not getting called. I have checked all my ID's and re ...

Error: Callstack Overflow encountered in TypeScript application

Here is the code snippet that triggers a Callstack Size Exceeded Error: declare var createjs:any; import {Animation} from '../animation'; import {Events} from 'ionic-angular'; import { Inject } from '@angular/core'; exp ...

Issue with ng-repeat not being filtered

Utilizing Salvattore (a masonry-like grid) within my Angular application, but encountering issues with the filter option in ng-repeat. It seems that Salvattore encapsulates each repeated item in an individual div to structure the grid (in this case, div.co ...

Loop through a vector or data frame in RCurl's postForm() function to input values into a text field form

My objective is to transmit each individual "finput" observation into an HTML form under the name "text". The process works smoothly when dealing with a single observation. However, I am encountering difficulties while attempting to iterate through the ve ...

Refresh the data using the Ajax function

I am attempting to implement a delete function using Ajax. function delCatItem(catitem){ var theitem = catitem; $.ajax({ url: "movie/deleteitem/", type: "POST", data: { "movieid" : catitem ...

The modification of input type is ineffective on Google Chrome and Safari browsers

I have encountered an issue where I am attempting to change a hidden input type into a file input type onclick of a button. The code works as expected on Mozilla Firefox and Internet Explorer, however, it does not function properly on Google Chrome and Saf ...

Why is my Angular router displaying the page twice in the browser window?

Angular was initially loading the page on the default port localhost:4200. I wanted it to serve as localhost:4200/specialtyquestions when the app builds, and that is working, but the pages are appearing twice in the browser. Any ideas on what might have be ...