Multiple image change on hover


I have a simple css hover function. I hover over tree-original.jpg and it changes to tree-2.jpg. It works fine.
Now I want to make things a bit complicated. I want to have multiple “hover” state images. So let’s say I hover over an image, and the image changes every 2 seconds to a different image.

For example, I have 4 images:

When I hover over tree-original.jpg I want tree-2.jpg to appear for 2 seconds, then tree-3.jpg for 2 seconds, then tree-4.jpg for 2 seconds (as long as the mouse is hovering over the image), and then back to tree-original.jpg. So as long as I have the pointer hovering over the image, the 4 images would be alternating every 2 seconds, forever (or until I move the mouse cursor).

Is that possible to do?

    <a href="home.html"></a>

div a {
    width:  200px;
    height: 200px;
    display: block;
    background-image: url('tree-original.jpg');

div a:hover {
    background-image: url('tree-2.jpg);

Update: I was hoping I could somehow achieve this with transition-delay property. I’m just not sure how to connect the dots

You could use @keyframes to do this by stacking the images horizontally (in an inner div) inside the 200px width div (hide the overflow) and then use translateX to move the inner container by 200px to reveal the next image.

Keyframes will allow you to do this continuously as you hover. You’d set a duration of 8 seconds and then move the container at 25% intervals.

1 Like

Here’s another similar way using multiple background images to achieve the effect.

Is there a way to make that work with :focus for keyboard access, @PaulOB? (I played briefly with your codepen, but I haven’t had my second cup of coffee yet. )

If you use an anchor then you can use :focus to trigger the animation also.

Demo updated above.:slight_smile:


Thanks, @PaulOB.

(That’s proof I hadn’t had enough coffee; that’s an easier fix than what I was trying. )

1 Like

Here’s another simple version for a slideshow effect on hover.


wow, this is much better than I imagined.

PaulOB - your code is amazing, so clean and everything! Thank you very, very much!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.