Explain Codes LogoExplain Codes Logo

How to change source of <img> tag on hover?

html
responsive-design
performance
css
Anton ShumikhinbyAnton Shumikhin·Oct 22, 2024
TLDR

Switching an <img> tag's source on hover can be accomplished neatly using CSS with the :hover pseudo-class. For a lean approach, let's trim this down to a single HTML tag complemented by CSS transitions. Consider this essential sample:

.img-hover { /* 'default.jpg' says: "You look fabulous today!" */ background-image: url('default.jpg'); width: 200px; /* Your image's glamorous width */ height: 200px; /* Your image's elegant height */ /* Who doesn't love a smooth change, huh? */ transition: background-image 0.5s ease-in-out; } .img-hover:hover { /* 'on-hover.jpg' whispers: "Wait till you see me on hover!" */ background-image: url('on-hover.jpg'); }

Kiss an <img> tag goodbye. Now, apply the .img-hover class to a <div> instead, and replace default.jpg and on-hover.jpg with your images to star in this hover effect feature. Let these transitions create a smooth cinematic change.

Not just a pretty face: enhancing accessibility

Visual appeal is crucial, but accessibility is the real beauty. Always put some heart into your images by providing meaningful alt text:

<div class="img-hover" role="img" aria-label="Descriptive text for your image"></div>

With role and aria-label attributes, you provide a VIP experience for assistive technologies. That's making a website more user-friendly.

Ensuring Visual Consistency: Cross-browser compatibility tips

Creating the perfect look can be a bit like a treasure hunt due to cross-browser compatibility quirks. Test your outcome on Chrome, Firefox, Safari, and Edge to ensure everyone experiences your website's pretty face. If you don't want to play the "does it look the same here" game, tools like BrowserStack or LambdaTest can do the job for you.

Get more control: JavaScript interactions

If you're craving for more intimacy with your images, JavaScript is like your personal cupid. By listening for mouseover and mouseout, it creates a unique interaction:

const img = document.querySelector('.image-selector'); // Mouseover says: "Surprise, here I am!" img.addEventListener('mouseover', () => img.src='hover-img.jpg'); // Mouseout whispers: "I'll be back!" img.addEventListener('mouseout', () => img.src='default-img.jpg');

These event listeners will make your images more than just a pretty face; they'll react to the user's desires directly.

Prioritizing Performance and Smooth transitions

A webpage's performance is the backbone of a great user experience. Handling images can be heavy, but with some tricks, you can keep your page feeling light and airy:

  • Leverage TinyPNG or ImageOptim to glamorize your website with optimized images without compromising their looks.
  • Showcase responsive images with the srcset attribute to stop wasting time on images larger than necessary.
<img src="example.jpg" srcset="example-480.jpg 480w, example-800.jpg 800w" sizes="(max-width: 600px) 480px, 800px" alt="A responsible example">

This little trick works like magic by providing the right image for each screen size and resolution.

Thinking Outside the Box: Alternative strategies

Need to interact with actual <img> tags instead of their CSS counterparts? Here are a couple of tricks up your sleeve:

  • Wrap it up: wrap the image with an element like a <div> and turn on the hover effect's runway lights by toggling its display property on hover:
<div class="image-wrapper"> <img src="default.jpg" alt="Default" class="default-image"> <img src="hover.jpg" alt="Hover" class="hover-image"> </div>
.hover-image { display: none; /* "I love to play hide and seek!" */ } .image-wrapper:hover .hover-image { display: block; /* "Here I am!" */ } .image-wrapper:hover .default-image { display: none; /* "Now it's my turn to hide!" */ }
  • Be a Picasso with Javascript: get more control for dynamic user delights beyond what CSS can offer.