Issue with fadeIn effect not functioning properly on the second child element

Requesting assistance with troubleshooting my code. The intended functionality is to animate the img tags using fadeIn and fadeOut, but currently only the first image fades out without the second image fading in. I suspect there may be an issue in my CSS that prevents the second image from displaying as intended. No error messages are being generated.

This involves one image overlapping another.

jQuery

$(document).ready(function() {
    $('.social-media a').on('mouseenter', function(e) {
        $(this).find("img:nth-child(2)").fadeIn();
        $(this).find("img:nth-child(1)").fadeOut();
    });
})

HTML

<div class="social-media">
    <a title="Share On Twitter" href="#">
         <img alt="" src="images/icon_twitter.png" />
         <img class="test" alt="" src="images/icon_twitter_active.png" />
</a>
</div>

CSS

.social-media {
    padding-top: 20px; 
    width: 166px; 
    margin: 0 auto 10px auto;
}
.social-media a {
    position: relative;
    width: 55px;
    height: 51px;
}
.social-media a img:nth-child(1) {
    opacity: 1;
}
.social-media a img:nth-child(2) {
    position: absolute;
    left: 0; top: -33px;
    opacity: 0;
    z-index: 2; 
}

Answer №1

Swapping out the technique of hiding the second <img> element with zero opacity, you might want to opt for using display: none instead:

.social-media a img:nth-child(2) {
    position: absolute;
    left: 0; top: -33px;
    display: none;
    z-index: 2; 
}

http://jsfiddle.net/8vH4E/

Nevertheless, I suggest considering a straightforward CSS image sprite approach to achieve the desired effect without needing JS.


Update: In response to the question about achieving this with CSS alone, I have adjusted the Fiddle to not use JS and simply rely on CSS along with pseudo-elements: http://jsfiddle.net/8vH4E/2/

.social-media a {
    display: block;
    position: relative;
    width: 100px;
    height: 100px;
    background-image: url(http://placehold.it/200x200);
    background-size: cover;
}
.social-media a::before {
    background-image: url(http://placehold.it/200x200/4a7298/eeeeee);
    background-size: cover;
    content: '';
    display: block;
    opacity: 0;
    pointer-events: none;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    -webkit-transition: all .25s ease-in-out;
    transition: all .25s ease-in-out;
}
.social-media a:hover::before {
    opacity: 1;
}

The plan here is quite simple:

  • Utilize background images instead. The sizing uses cover, but feel free to choose any sizing method (absolute pixel/point sizes, relative percentage sizes, or dynamically-computed like cover, contain)
  • For hover effects, employ an absolutely-positioned pseudo-element that covers the entire <a> (by positioning it absolutely with zero offsets in all directions). Exclude pointer events on the pseudo-element by setting pointer-events: none
  • When hovering over the <a> element (targeted with :hover selector), switch the opacity of the pseudo-element from 0 to 1. Include the transition property on the pseudo-element for smooth transitions handled by browsers independently of JS.

Answer №2

The graphic looks nice, but the transition could be smoother (I believe that was the main issue, wasn't it?).

Let's improve the current code:

  1. When using fadeOut(), make sure to set the element to display: none; state first, as fadeIn() starts when the element is in that state. So, initially hide the second image by setting it to display: none;;

  2. We can remove the opacity adjustments for both images and rely on the default value of 1.0; $.fadeIn/Out() will use the opacity values from the CSS for the animation. However, you can specify opacity for each image if needed;

  3. Using display: inline-block; for the <a> tag is important because it contains inline elements which might disappear (display: none;), causing the entire <a> tag to vanish and triggering unexpected UI issues during mouseleave events.

Check out this example http://jsfiddle.net/8vH4E/1/ and shoutout to Terry for creating the fiddle :)

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

Trouble aligning CSS Nav Bar to the right with Flexbox

Having some trouble with implementing "flex" in CSS. My nav bar just won't move to the right no matter what I try. Spent hours adjusting margins, displays, and floats but it's stuck in the middle... Still learning, so any help is appreciated! If ...

Display all files within every subdirectory located in a specified folder on Google Drive

Recently, I stumbled upon a script located at https://github.com/bluexm/snipets/blob/master/list%20Gdrive%20files%20and%20folders. The challenge I encountered was that the script was not capable of handling folders with identical names. As a result, I made ...

Retrieve the value from the URL by parsing it using JSON

My goal is to extract the asciiName from a specific URL: http://services.gisgraphy.com/geoloc/search?lat=21.283300399780273&lng=72.9832992553711&radius=10000<br> I am utilizing ajax jsonp for this task. Below is the complete code snippet ...

"Exploring three.js: Transforming a plane's orthogonal vector into a rotation matrix for the plane

I am trying to set the rotation of a plane by using three numbers representing the rotation in radians along the x, y, and z axes. Although I do not have these numbers, I do have a vector called 'myVec' which should be orthogonal to the plane af ...

What is the method for extracting information from a dropdown menu using AJAX and transmitting it to a PHP script?

Looking to obtain the name of the selected category from a drop-down list using AJAX and send it to the PHP page containing the AJAX script. Here is the updated code: Action code: public function actionCreate() { $model=new News; // ...

Interactive Image with Description and Redirect

Hey, I'm trying to figure out how to create something similar to the image shown in this picture: example I attempted using Bootstrap grid but I keep ending up with a border around the edges. Any suggestions? ...

Tips for effectively integrating d3 as a Laravel dependency and linking it to a constant:

I've been working on implementing d3 into my Laravel project. Following this helpful tutorial as a guide. Starting with a new Laravel project, I made some modifications (switched to Foundation from bootstrap), and installed the necessary d3 modules. ...

Pairing two actions with a single event

I am looking to connect two events together. Currently, I have set up a binding for all mouse actions to a canvas and then utilize a wrapper function to adjust the mouse position relative to the canvas. This wrapper function then triggers the appropriate ...

JQuery: Unacknowledged Modifications to Classes

Currently, I am developing a platform for creating and managing workout logs. I am now working on the interface that team administrators will use to oversee their team members. To help you envision what the member management bar looks like, I have included ...

Extract the text located within a specific span using Selenium

Can anyone help me retrieve the value from the span tag in this scenario? The class name is consistent, but if there is an error in any of the fields belonging to that class, the text will become visible. For instance, consider the following two fields: ...

View Preview Image using the following image tag in JavaScript

I am trying to display an image preview using the img tag that is placed after my input field. Here is my HTML: <input name="image" type="file" id="uploadImage" onchange="PreviewImage(this);" /> ...

Sending checkbox selections to JavaScript

I am currently exploring Angular by working on a chat application project. My main focus right now is on passing checkbox values to my JS code. I have included snippets of the code below. The issue I'm encountering is that I can't seem to retriev ...

Attempting to divide the given web address

Is there a way to divide the URL below into components and extract only "store" from it? http://www.store.com/products.aspx/Books/The-happy-donkey If so, what would be the best method to achieve this? ...

Combining D3 and D3plus in an Angular web application: A complete guide

I'm currently integrating d3Plus sample code () into my angular-based webapp. This is the initial setup code: angular.module('UI', ['UI.controllers', 'UI.directives']); angular.module('d3Plus', ['d3' ...

In a production environment, jQuery's ajax functionality may encounter issues specifically on Internet Explorer

I am experiencing an issue with making a service call using jQuery's ajax function. During testing on my local environment in both IE and Chrome, the call works properly. However, once our site is deployed to production, I can only get the service cal ...

Utilize getJSON to refresh the JavaScript datetimepicker

I am currently using an api with ajax (getJSON) to append data to a specific div called 'open' on my website. However, I now want to update the static values in my datetime picker script for minTime and maxTime. Here is the code snippet: AJAX ...

Each time guildMemberAdd is triggered in Discord.js, it may not run consistently

At times, I am left baffled by the inconsistency in behavior of this code. Sometimes it works like a charm, while other times it refuses to add people for hours on end, only to randomly start working again. Any suggestions on how I can resolve this issue? ...

Consistent header and footer that remain fixed at the top and bottom of each page

Is there a way to have a fixed header at the top and a footer that always stays at the bottom of the page using CSS, without relying on a master page? ...

Display fewer categories (list items) on mobile and medium-sized devices

I need assistance with modifying a code snippet to display a menu with categories. Here's the current code: <div class=" d-md-block"> <div class="container"> <div class="row"> <div class="co ...

Passing PHP success and error messages to Javascript

I am currently working on a feature that displays success and error messages once a form is submitted. Here's an overview of how the form functions: Users can modify their posts by clicking the edit button, which transforms the <div> containin ...