I have a page with several images on it. When the user hovers over any one of the images, I would like a 50% opaque overlay div to fade in with information about the image being hovered over. Here is the code I have in the PHP just now (I’ve removed the string concats etc for easier reading):
<div class="propertyoverlay"
id="boxnum'.$propertynumber.'"
onMouseOver="fadein(\'boxnum'.$propertynumber.'\')"
onMouseOut="fadeout(\'boxnum'.$propertynumber.'\')"
>';
<h3 class="price">'.$properties[$propertynumber]['price'].'</h3>';
</div>';
Which feeds the div ID over to the following commands:
function fadein(id){
$('#'+id).animate({ 'opacity': 0.5 });
}
function fadeout(id){
$('#'+id).animate({ 'opacity': 0 });
}
The issues I’m having are:
A. if a user hovers on and off from the image repeatedly and quickly, the fade commands stack up. It would be nicer if the mouseOver and mouseOut commands just overwrote the rest of the cue as soon as they were called.
B. When I hover over the H3 tag nested inside the parent, the mouseOut is called directly followed by the mouse over command, causing the div to fade out and then fade in again straight away.
I’m happy to use Javascript or JQuery to solve this, but, if at all possible, would rather avoid a CSS3 based solution for the time being. Thanks very much for your time!
A: Use the jQuery .stop() method before calling animate, eg:
B: Try using the
mouseenterandmouseleaveevents in jQuery (docs). This will fix the issue with child elements triggering mouseover/mouseout. This means you will have to bind the events with jQuery however, not directly on the HTML elements.