Unable to get CSS transition to function properly after adding a class using jQuery

I am trying to create a hover effect that shows an image when the mouse is over a specific div, but for some reason, the transition is not working as expected. I understand that using visibility: hidden cannot be animated.

Here is the code snippet:

$(document).ready(function() {
    
    $("#trigger").on("mouseenter", function () {
        $("#imgPuffo").addClass("visible");

        $("#trigger").on("mouseout", function () {
            $("#imgPuffo").removeClass("visible");
        });
        
    });

});
#trigger {
        height: 100px;
        width: 100px;
        background: red;
    }
    img {
        opacity: 0;
        animation: opacity 2s;
    }
    .visible {
        visibility: visible;
        opacity: 1;
        animation: opacity 2s;
    }
    .imgPuffo {
        height: 200px;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="trigger"></div>
    <img id="imgPuffo" class="imgPuffo" src="https://www.pinclipart.com/picdir/big/449-4499911_how-to-draw-papa-smurf-from-the-smurfs.png" alt="">

Answer №1

There seems to be some confusion with the use of animations in this code snippet. Typically, animations require an @keyframes sequence to specify the animation. However, a CSS transition might suffice in this case without needing a full CSS animation.

To achieve a transition effect, transition: all 2s has been included for future transitions. If only transitioning opacity is desired, you can use transition: opacity 2s instead.

$(document).ready(function() {
    
    $("#trigger").on("mouseenter", function () {
        $("#imgPuffo").addClass("visible");

        $("#trigger").on("mouseout", function () {
            $("#imgPuffo").removeClass("visible");
        });
        
    });

});
#trigger {
        height: 100px;
        width: 100px;
        background: red;
    }
    img {
        opacity: 0;
        /* animation: opacity 2s; */
        transition: all 2s;
    }
    .visible {
        visibility: visible;
        opacity: 1;
        /* animation: opacity 2s; */
    }
    .imgPuffo {
        height: 200px;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="trigger"></div>
    <img id="imgPuffo" class="imgPuffo" src="https://www.pinclipart.com/picdir/big/449-4499911_how-to-draw-papa-smurf-from-the-smurfs.png" alt="">

Answer №2

For those interested in utilizing animations, please refer to the documentation where you will find information on using @keyframes.

$(document).ready(function() {
    
    $("#trigger").on("mouseenter", function () {
        $("#imgPuffo").addClass("visible");

        $("#trigger").on("mouseout", function () {
            $("#imgPuffo").removeClass("visible");
        });
        
    });

});
#trigger {
        height: 100px;
        width: 100px;
        background: red;
    }
    img {
        opacity: 0;
        animation: opacity 2s;
    }
    .visible {
        visibility: visible;
        opacity: 1;  
        
        transition: opacity 2s ease-in-out;
        
    }
    .imgPuffo {
        height: 200px;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="trigger"></div>
    <img id="imgPuffo" class="imgPuffo" src="https://www.pinclipart.com/picdir/big/449-4499911_how-to-draw-papa-smurf-from-the-smurfs.png" alt="">

Answer №3

Looking for a CSS solution utilizing the :hover pseudo-class without the need for jQuery?

#trigger {
  height: 100px;
  width: 100px;
  background: red;
}
    
#trigger:hover + .imgPuffo {
  opacity: 1;
}

.imgPuffo {
  opacity: 0;
  height: 200px;
  transition: opacity 2s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="trigger"></div>
<img id="imgPuffo" class="imgPuffo" src="https://www.pinclipart.com/picdir/big/449-4499911_how-to-draw-papa-smurf-from-the-smurfs.png" alt="">

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

Showing JSON data using CSS and HTML

Hello there! I've come across a coding hurdle today. I attempted to retrieve JSON data from a URL using the following PHP code snippet: <?php $url = "http://services.faa.gov/airport/status/LAX?format=json"; $ch = curl_init(); curl_setopt($ch,CURL ...

The sub menu in IE 8 does not stay open while hovering over it

My website has a navigation menu with a sub-menu that appears when hovering over the parent element. While this works smoothly on modern browsers, Internet Explorer 8 presents an issue. When hovering over the parent li element in IE 8, the sub-menu is disp ...

What is the best way to include a variable or literal as a value in styled components?

When it comes to managing various use cases, I always rely on props. However, I am currently facing a challenge in changing the border color of a styled input during its focus state. Is there a way to utilize props for this specific scenario? Despite my f ...

Bypass the typical practice of choosing input with javascript

I have a form with a select input that has a dropdown list of options. The requirement is that when the select input is clicked, I need to validate the form. If the form is incomplete, I want to prevent the select input from showing the option list. Howeve ...

`Count the number of rows needed to accommodate text line breaks within a div element`

Is there a method to determine the number of lines that text breaks into using the CSS property word-break: break-all? For example, if I have a div like this: <div>Sample text to check how many lines the text is broken into</div> And the corr ...

Error encountered in VUE JS 3: The function vue.initDirectivesForSSR is not recognized as a valid function

I've been encountering some errors while trying to build my Vue web app with this configuration. I have searched for a solution, but couldn't find anyone facing the same issue as me. Any suggestions on how to resolve this problem? The build was s ...

How can I access dynamically created input elements without using $refs, such as getting focus?

Is there a way to handle dynamically created inputs for editing purposes without using jQuery or vanilla JS all the time? Each input element has its own ID and is displayed through v-if when editing is triggered. However, Vue does not recognize them in r ...

Navigating in AngularJS with various URL parameters

Within my application, I am in need of using routes that require multiple attributes from the URL to be passed into PHP. The current setup that is functioning correctly is as follows: .when('/jobs/:type', { templateUrl: function(attrs){ ...

Encountering a problem with TypeScript while employing Promise.allSettled

My current code snippet: const neuroResponses = await Promise.allSettled(neuroRequests); const ret = neuroResponses.filter(response => response?.value?.data?.result[0]?.generated_text?.length > 0).map(({ value }) => value.data.result[0]?.genera ...

The information is failing to display properly within the mat-menu

Recently, I've been working on creating a navbar that includes a submenu. Even though the navigation bar data is loading properly, I am facing some issues with the submenu functionality. As a beginner in this area, I would appreciate any help or guida ...

Guide to dynamically setting a value in an input field using JavaScript's document.querySelector

My goal is to input a value using Javascript. Check out my project link! Click on "add to cart" and then proceed to checkout to reach the checkout page. I am trying to automatically add a Zipcode value to the checkout page. I attempted this method but it ...

A step-by-step guide on using Javascript to transform images into text

Hey there! I'm looking for some help to convert an image into text. The idea is that when someone uploads an image and hits the "Submit" button, the text from the image should display in a textarea below. However, the code I've been working on do ...

What is the best way to programmatically change the event tied to an element's click

<div id="filters"></div> <div id="available"> <span class="badge badge-pill" onclick="addFilter()">Label</span> </div> function addFilter(event) { document.getElementById("filters").appendChild(eve ...

Creating a flexible route path with additional query parameters

I am facing a challenge in creating a unique URL, similar to this format: http://localhost:3000/boarding-school/delhi-ncr However, when using router.push(), the dynamic URL is being duplicated like so: http://localhost:3000/boarding-school/boarding-school ...

Unable to find the specified element within the dropdown menu

Trying to figure out how to distinguish my xpath from the following: <td onclick="hrefClick(this,4,0);" onmouseout="menuLevel2MouseOut(this);" onmouseover="menuLevel2MouseOver(this);" style="padding-left:30px; padding-top:10px; padding-b ...

Escaping back slashes in Node.js

I am currently encountering an issue with escaping backslashes. Below is the code snippet that I have attempted. The problem lies in how to assign a variable containing an escaped slash to another variable. var s = 'domain\\username'; ...

Incorporating fresh data from a node.js backend to refresh a webpage section

I'm currently working on creating an app that can retrieve the song a user is currently listening to using a web scraper. While I've managed to direct users to the page and display the current song title, they must manually refresh the entire pag ...

Items in a CSS masonry container with a 'column count' feature showcasing drop shadows that elegantly span across multiple lines

I've been experimenting with CSS column count to create a masonry effect for my items. Everything was going smoothly until I added a subtle drop shadow to the items. Upon closer inspection in the jsfiddle link provided, you'll notice that the dr ...

The issue I am facing involves a 404 not found axios error when attempting to send a post request

I am attempting to send data via a post request from react.js to express.js using axios, but I keep encountering a 404 not found axios error. You can view the error image here. Below is my code: export default function Upload() { const [state, setState ...

Making a Cross-Origin Resource Sharing (CORS) request with jQuery utilizing the $

I am currently in the process of building a web application that relies heavily on data from multiple domains. Approximately 90% of the requests made by my application are cross-domain requests. However, I have encountered an issue where I am unable to re ...