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

Guide on launching a mobile application upon clicking a button in a mobile browser (with the assistance of JavaScript/React) [Utilizing Deep Linking]

My goal is to create a functionality where, on a mobile browser, when the user clicks on a button: If the app is already installed on the user's mobile device, it should open up. If the app is not yet installed, I aim to redirect the user to the appr ...

The objects-to-csv module encountered an error: fs.existsSync is not a valid function for this

"TypeError: fs.existsSync is not a function" Whenever I try to create a CSV file and input some data into it, this error message pops up. const objectstocsv = require('objects-to-csv'); export default { data () { return { ...

Retrieve information from MySQL database with jQuery upon button click

After fetching multiple data rows from a MySQL database and displaying them in a table, I want to include a button in the last column of each row. The unique ID for each button will be retrieved from the database. When a user clicks on any of these buttons ...

Identify the month in which there is no data available in the database

The existing query is working perfectly, but the issue is that there is no data for the current month (April), causing it not to list the month with 0 interviews. How can I make it so that the month is listed with 0 interviews? QUERY select distinct from ...

What is the best approach to modifying the color of a menu item in the sidebar upon clicking it using Material-UI in a React application?

I am a beginner with this framework and my goal is to change the color when clicking on a Menu Item in the Sidebar. For example, clicking on the table component should change the table name and icon to white color. Could someone please help me figure out h ...

CSS-only: Align items in flexbox column with equal width and centered position, without the need for a wrapper

https://i.stack.imgur.com/vAJv2.png This particular challenge involves creating a responsive mobile menu. In this design, the width of all children is determined by the longest child element. The CSS should ensure that the .index class spans the full wi ...

Fixed css footer with full height content container

For my website's sticky footer, I followed this technique: I wanted to add a border around the entire site that also encompasses the footer, but ran into an issue where it did not extend around the page properly. Here is what happened: You'll n ...

What is causing the content to appear cluttered inside the jQuery Dialog Box?

$(document).ready(function() { $('.something').each(function() { var $link = $(this); $link.click(function() { var $dialog = $('<div></div>') .load($link.att ...

Having difficulty communicating with the smart contract using JavaScript in order to retrieve the user's address and the balance of the smart contract

Hi there, I am a newcomer to the world of blockchain technology. Recently, I created a smart contract designed to display both the contract balance and user data, including the address and balance of the user. The smart contract allows users to deposit fun ...

What is the best way to incorporate a @types module into a TypeScript file that is not already a module?

Setting the Stage: In the process of shifting a hefty ~3,000 line inline <script> from a web-page to a TypeScript file (PageScripts.ts) to be utilized by the page through <script src="PageScripts.js" defer></script>. This script entails ...

What is the best way to assign three different dates in my protractor test?

I am facing an issue with setting random dates in 3 date fields in a row using Protractor. The problem is that Protractor sets the dates too quickly and sometimes assigns invalid dates like: first data: 01/08/1990 (correct) second data: 01/09/0009 (inva ...

Tips for adding images using v-for in Vue 3

Having some trouble creating a set of images using a v-for loop, as it seems to be not recognizing the variables inside the tag. The picture is broken and the alt attribute just shows me {{ item.alt }}. Here is my HTML: <section class="our-technolo ...

Using Backbone.js to Retrieve Data from the Server and Bind it to a Model

Having recently delved into Backbone.js, I found this informative tutorial quite helpful in getting started. Now, I am looking to take things a step further by fetching data from the server instead of hardcoding values in JavaScript as demonstrated in the ...

Tips for utilizing the async.js library in combination with the await keyword?

Currently, I am working on integrating the async library to continuously poll an API for a transaction until it is successful. router.get('/', async function (req, res) { let apiMethod = await service.getTransactionResult(txHash).execute(); ...

React Modals: Only the modal component triggered by the first click will open, with no other modals opening

As a newcomer to StackOverflow, I apologize if my problem description is not clear. I am currently learning React and working on a course-search app as a project. The app filters courses based on user input from a JSON file and displays them in cards with ...

Executing Javascript on Selenium RC with PHP is a crucial skill to have in your toolkit

Is there a way to execute Javascript from Selenium RC? I have been trying different methods with no success so far. I attempted the following approach: I created a custom function in user-extensions.js: function sayhello() { document.write('hel ...

Divide the identical elements and distinct elements from a provided array into two separate arrays storing unique elements and recurring elements

Can anyone help me with this query? I have an array of objects that need to be separated into repeating and non-repeating objects based on the segments they belong to, each in a separate array. For example- [ {name:"abc",id:1,segments:[1,2]}, {n ...

Reveal or conceal interactive material using data attributes

I am having difficulty in achieving a certain functionality on my website. Here is the HTML code I am using: <div id="menu"></div> <ul class="countries"> <li data-country="country-1" data-countryname="France">Category France</ ...

issues stemming from the css of leaflets

This is my first time using leaflet and I am encountering a CSS issue. I'm not sure if there is another CSS file for leaflet, but whenever I try to adjust its position, it changes unexpectedly. I have a floating nav bar that should appear when scroll ...

Is there a way to ensure consistent border thickness in a material-ui table layout?

In my current setup of a material UI table, I have applied a 1-pixel thickness to all elements. This leads to a slightly thicker appearance at the points where two cells meet compared to the outer edges. How can I achieve a consistent border width of 1px ...