Dove Man Dove Man - 1 month ago 8
CSS Question

Add timer to change image on hover

So here's my code and the jsfiddle. The effects works great, only thing is I have no idea how to add a timer to it.

E.g. When someone hovers over the image, it doesn't change the image instantly. You have to keep the cursor over it for 10 seconds before it will change.

HTML

<a href="https://www.google.com/"><img src="chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-translate-content.png" onmouseover="this.src='chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-images-content.png'" onmouseout="this.src='chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-translate-content.png'" /></a>

Answer

This can be achieved by setting a timeout in JavaScript.

var timer;

document.getElementById('img-hover').addEventListener('mouseover', function() {
    clearTimeout(timer);
    var elem = this;
    timer = setTimeout(function() {
        elem.src='chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-images-content.png';
    }, 1000);
});

document.getElementById('img-hover').addEventListener('mouseout', function() {
    clearTimeout(timer);
    var elem = this;
    timer = setTimeout(function() {
        elem.src='chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-translate-content.png';
    }, 1000);
});

You also need to include an ID and remove the inline click events in your HTML, so it should be this:

<a href="https://www.google.com/"><img id="img-hover" src="chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-translate-content.png"/></a>

JSFiddle

Note that in the JSFiddle, I did have to change the images so I can actually see them :)

Comments