Reputation: 255
I have a set of images that for each one I would like to rollover and flicker to a different image for half a second or so, then revert back to the original image, even if the mouse is still over the image (ie there's no mouseout)
setTimeout was suggested but I can't figure out how to use it properly.
There's an example of the page....I'd just like the image that appears on rollover to appear then disappear again quickly.
I've scoured the web for examples and can't find anything...any help would be greatly appreciated.
Thanks, Andrew
Edit:
This is the code I'm currently using for hover 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);
});
});
});
Upvotes: 2
Views: 5564
Reputation: 6147
There is better way that setTimeOut
you can use $('.rollover').mouseenter(function() {
instead of $('.rollover').hover(function() {
http://api.jquery.com/mouseenter/
Upvotes: 0
Reputation: 51685
Using setTimeout
is easy. It takes a function as the first argument — just like many jQuery methods — and the time in milliseconds as the second.
I started with your code and refactored it a bit. Originally, there would have been the potential for a race condition if the user mouses over, away from, and then back over the image before the timer fires. Now, the logic for switching to the alternate image and back to the original is separate. The mouseover handler also short-circuits if the images are already swapped out. I also cache the jQuery object returned by $(this)
, for a slight speed improvement (caching jQuery objects is good practice).
I changed the hover
attribute to data-hover
(the HTML5 spec lets you use custom attributes but requires that they start with data-
) and checked for its presense in the mouseover selector.
Finally, I removed the extra ready
wrapper ($(document).ready(function(){…})
and $(function(){…}
are the same, no 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.
Upvotes: 7
Reputation: 923
Something like
$('#myid').hover(function() {
$(this).addClass('hovered');
setTimeout(function() { $('#myid').removeClass('hovered'); }, 100);
});
Upvotes: 0
Reputation: 8166
Here you can find some clear examples:
http://www.electrictoolbox.com/using-settimeout-javascript/
But I would personally advice you to use the Timers plugin, which is more friendly to use: http://jquery.offput.ca/every/
Upvotes: 0