Transition smoothly between two images with CSS or jQuery

I am working on a project where I need to implement a hover effect that fades in a second image above the initial image. The challenge is to ensure that the second image remains hidden initially and smoothly fades in without causing the initial image to fade out completely. I have experimented with various methods including using one image, two images, jQuery animate, and CSS transitions.

I have come across information suggesting that it is possible to animate changes in attributes using jQuery. If this is indeed true, I would like to know how I can animate the change of the 'src' attribute in an img element using jQuery.

$(".image").mouseenter(function() {
        var img = $(this);
        var newSrc = img.attr("data-hover-src");

        img.attr("src",newSrc);
        img.fadeTo('slow', 0.8, function() {
            img.attr("src", newSrc);
        });
        img.fadeTo('slow', 1);
}).mouseleave(function() {
        var img = $(this);
        var newSrc = img.attr("data-regular-src");

        img.fadeTo('slow', 0.8, function() {
            img.attr("src", newSrc);
        });
        img.fadeTo('slow', 1);
});

The code snippet above is what I am currently using, which has brought me closest to achieving the desired outcome. However, there is still a slight flicker during the image change, which is not ideal.

Answer №1

Creating a Stylish Image Effect Using CSS

Here's a simple way to add stylish hover effects to images using just HTML and CSS.

<div id="imgHolder"></div>

CSS

#imgHolder {
    width: 200px;
    height: 200px;
    display: block;
    position: relative;
}

/*Initial image*/
 #imgHolder::before {
    content:"";
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    position: absolute;
    background-image:url(http://placehold.it/200x200);
    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
    transition: opacity 1s ease-in-out;
    z-index:10;
}

#imgHolder:hover::before {
    opacity:0;
}

#imgHolder::after {
    content:"";
    background: url(http://placehold.it/200x200/FF0000);
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    position: absolute;
    z-index: -1;
}

See Demo Here

Another Option Using Image Tags

If you prefer using image tags, check out this example:

HTML

<div id="cf">
  <img class="bottom" src="pathetoImg1.jpg" />
  <img class="top" src="pathetoImg2.jpg" />
</div>

CSS

#cf {
  position:relative;
  height:281px;
  width:450px;
  margin:0 auto;
}

#cf img {
  position:absolute;
  left:0;
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

#cf img.top:hover {
  opacity:0;
}

You can find more examples on the provided link. Have fun experimenting!

Adjusting Opacity Levels

If you want to control how much of the initial image remains visible after hovering, simply adjust the opacity value in the CSS code. Try different values until you achieve your desired effect.

Demo with adjusted opacity

Dynamic Image Sizes

If you need flexibility with image sizes, consider using the two-image version described earlier. The CSS will remain similar, but you can adjust it based on your needs.

See Dynamic Image Sizes Demo Here

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

Breaking down an object containing an internal array and omitting specific keys

I've got this specific object structure: const objBefore: { "id": "3pa99f64-5717-4562-b3fc-2c963f66afa1", "number": "5000", "enabled": true, "classes": [ { ...

What is the most efficient method for integrating PHP script into HTML code?

When it comes to inserting the full path to every image/css file on my website due to url rewriting, I am searching for the most efficient method. I could simply use: <img src='<?php echo $full_path; ?>/images/theImg.jpg' alt='alt ...

Is there a way to adjust the placement of the h1 tag using the before pseudo-element?

I'm looking to place an image on the left side of each h1 tag. I've been attempting to utilize the before pseudo element for this task. The issue arises when there is no content, causing the before pseudo element to overlap with the h1 tag. How ...

When you set the href attribute, you are essentially changing the destination of the link

UPDATE: I'm not referring to the status bar; instead, I'm talking about the clickable text that leads to a link. /UPDATE I've gone through a few similar posts but couldn't find a solution. I have a link that needs to be displayed. www ...

Struggling to properly implement background images in a React application using Tailwind CSS

I'm currently developing a React application using Tailwind CSS for styling. In my project, I have an array of items called "trending," and I'm attempting to iterate through them to generate a series of divs with background images. However, I am ...

Manually browse through images in photoswipe by clicking on them to move to the previous or next ones

Utilizing photoswipe within my mobile app has been a seamless experience. Instead of utilizing the full screen view, we are displaying images within a target div. A new requirement was introduced to hide the built-in toolbar and incorporate arrow buttons ...

What's the best method for efficiently hiding/showing a large number of DOM elements?

Imagine you have a maximum of 100 elements that remain consistent in type and format, but their content changes. These elements are connected to an input field and will update as the user types. What would be the most efficient approach for maximizing per ...

An issue arises with the Datatables destroy function

Utilizing datatables.js to generate a report table on my page with filters. However, when applying any of the filters, the data returned has varying column counts which prompts me to destroy and recreate the table. Unfortunately, an error message pops up ...

Activate the popup for sharing or bookmarking by clicking on a regular link

I am currently utilizing a Share/Bookmark script: <div class="singles-right"> <a href="#" class="bookmark"></a> <script type="text/javascript" src="http://static.addinto.com/ai/ai2_bkmk.js"></script> <a href="#" clas ...

Unable to make a successful POST request using the JQuery $.ajax() function

I am currently working with the following HTML code: <select id="options" title="prd_name1" name="options" onblur="getpricefromselect(this);" onchange="getpricefromselect(this);"></select> along with an: <input type="text" id="prd_price" ...

Getting data from an HTML file with AJAX

I have a JavaScript application where I am trying to retrieve an HTML file in order to template it. Currently, I am using the following method: var _$e = null; $.ajax({ type: "GET", url: "/static ...

The sharing feature is not functioning properly within content loaded via AJAX

My website has a feature that dynamically pulls in content using AJAX requests and JQuery. After the content is loaded, I use colorbox's onComplete function to load any necessary scripts. One of the things I'm trying to load is a ShareThis button ...

Are cookies always included in client requests?

With every interaction between the server and browser, cookies are exchanged back and forth. However, what happens when an image is requested? <img src='myPic.jpg' /> Is the browser also sending cookies during this type of request? If i ...

Can CSS alone be used to provide a cover for auto-scaling images?

One common technique is using max-height and max-width to make an image automatically fit in a div, as shown below: .cover img { max-width: 100%; max-height: 100%; } But is there a way to create a translucent cover (with opacity set to 0.8) that ...

What is causing the fs.readFile function to give back undefined instead of the expected result?

/** * A function to determine the cost of an employee from a specific data file * @param {string} filePath - the path to the employee data file * @returns {{name: string, cost: number}} - the name and cost of the employee */ function calculateEmployee ...

How React Utilizes Json Arrays to Add Data to a File Tree Multiple Times

For some reason, when attempting to add data to a file tree, it seems to duplicate the data sets. I'm not entirely sure why this is happening. Here's an example of the simple json array I am working with: export const treeDataFile = [{ type: & ...

Transforming a Python list into a JavaScript array

Hey there, I'm in the process of creating a JavaScript array of dates to input into a jQuery datepicker addon. Here is my Django view: def autofill_featured(request): show_id = request.GET.get('show_id') show = Show.objects.get(id=s ...

AngularJS chatbox widget for interactive communication

Currently, I am in the process of developing the back-end for a web application utilizing angularJS. One of the key features is allowing users to communicate with each other through a pop-up chat box similar to those found in Gmail or Facebook. My goal is ...

I am encountering an issue with identifying a directory in Node.js

This is my HTML code <div id="done_work_1" class="logo-slide-track"> </div> <script>$.ajax({ url: "/static/home/done/", success: function (data) { $(data).find("a").attr("href&q ...

Ways to repair the mouse hover transform scale effect (animation included)

I am currently facing an issue with my GridView that contains images. When I hover over the top of the image, it displays correctly, but when I move to the bottom, it does not show up. After some investigation, I suspect that there may be an overlay being ...