JQuery hover with setTimeout (opposite hoverIntent)
I have a set of images that, for each of them, I would like to flip and flicker onto another image for half a second or so, and then revert to the original image, even if the mouse is still over the image (i.e. no mouse )
setTimeout has been suggested, but I can't figure out how to use it correctly.
Here's a sample page .... I would like the rollover image to appear, then quickly disappear.
I have looked through the webpages for examples and cannot find anything ... any help would be greatly appreciated.
Thanks Andrew
Edit:
This is the code I am currently using to create images
$(document).ready(function(){
$(function() {
$('.rollover').hover(function() {
var currentImg = $(this).attr('src');
$(this).attr('src', $(this).attr('hover'));
$(this).attr('hover', currentImg);
}, function() {
var currentImg = $(this).attr('src');
$(this).attr('src', $(this).attr('hover'));
$(this).attr('hover', currentImg);
});
});
});
a source to share
The use is setTimeout
very simple. It takes a function as its first argument - like many jQuery methods - and a time in milliseconds as its second.
I started with your code and reworked it a bit. There would initially be the potential for a race condition if the user transitions, walks away, and then back through the image before the timer fires. Now the logic for switching to an alternate image and back to the original is separate. The mouse handler also closes if images have already been unloaded. I also cache the jQuery object returned $(this)
for a slight speed improvement (caching jQuery objects is good practice).
I changed the attribute hover
to data-hover
(HTML5 spec allows custom attributes, but requires them to start with data-
) and checked for its presence in the mouse selector.
Finally, I removed the extra packaging ready
( $(document).ready(function(){…})
and $(function(){…}
- same thing, you don't need to have both of them).
$(function() {
$('.rollover[data-hover]').mouseover(function() {
var $this = $(this), originalImage = $this.attr('src');
if ($this.data('imagesSwapped')) {
return;
}
$this.attr('src', $this.attr('data-hover')).data('imagesSwapped', true);
setTimeout(function(){
$this.attr('src', originalImage).removeData('imagesSwapped');
}, 500);
});
});
The code has not been tested.
a source to share
You can find some clear examples here:
http://www.electrictoolbox.com/using-settimeout-javascript/
But I will personally advise you to use the Timers plugin, which is more convenient to use: http://jquery.offput.ca/every/
a source to share
There is a better way to setTimeOut
you can use $('.rollover').mouseenter(function() {
instead $('.rollover').hover(function() {
http://api.jquery.com/mouseenter/
a source to share