In a recent project, I was attempting to dynamically display an overlay on top of an image that contained the image’s alternative text. The overlay was to display whenever the mouse hovered over said image and hide once the mouse blurred on the image.

Unfortunately, my first attempt at this resulted in a lot of flickering.

Initially, I was trying to achieve this by positioning and displaying the overlay when the mouse hovered over the image and hiding the overlay whenever the mouse blurred on the image.

As mentioned, this caused flickering every time the mouse moved across the image. Specifically, the overlay would quickly toggle on an off as the mouse moved across the image.

My original code looked something like this:

$(function() {

	$('#main img').hover(function() {
		$('#caption')
			.text($(this).attr('alt'))
			.css({
				left: $(this).position().left,
				top: $(this).position().top,
			}).show();
	}, function() {
		$('#caption').hide();
	});

});

The problem was that the overlay was on top of the image so attempting to hide the overlay when the mouse blurred on the image was incorrect.

Instead, the overlay should display when the mouse hovered over the image and hide when the mouse blurred on the overlay (rather than the image).

Here’s the final version of the working script:

$(function() {

	$('#main img').hover(function() {
		$('#caption')
			.text($(this).attr('alt'))
			.css({
				left: $(this).position().left,
				top: $(this).position().top,
			}).show();
	});

	$('#caption').mouseout(function() {
		$(this).hide();
	});

});
Category:
Notes
Tags:

    Leave a Reply