I've managed to get my hover effect working, but I'm looking for ways to optimize it as there seems to be some lag when the script is searching for the .overlay
div. I also made the mistake of animating all .overlay
divs on the page, which I now realize was a beginner error.
So, let's explore how we can improve the code below!
jQuery:
// fetch aside feature
var aside_feature = $('aside .feature');
// fade it in on hover
$( aside_feature ).hover(function() {
// find the overlay div
var feature_overlay = $(this).find('.overlay');
$(feature_overlay).stop().fadeIn();
// fade it out on hover out
}, function() {
$(this).find('.overlay').stop().fadeOut();
});
Markup:
<aside>
<div class="feature">
<div class="overlay">
<a href="">button</a>
</div><!-- overlay -->
<div class="text">
<p>text</p>
</div><!-- .text-->
<div class="image">
<figure>
<img src="" alt="">
</figure>
</div><!-- .image -->
</div><!-- .feature -->
</aside><!-- aside -->
Fiddle: http://jsfiddle.net/9xRML/5/
Edit - Final Code
Many thanks to @Shomz and @Afro.
After considering various options, I decided to incorporate transitions, along with utilizing modernizr for detecting CSS transition support detection for transitions. I changed the hidden overlay div to have opacity: 0; *display:none;
and used JavaScript as a fallback:
CSS
.overlay {
*display: none;
opacity: 0;
transition: 0.4s all linear;
}
.overlay:hover {
opacity: 1;
}
jQuery
$(function () {
/*=====================================
= Feature overlay =
=====================================*/
if (!Modernizr.csstransitions) {
// get aside feature
var aside_feature = $('aside .feature');
// on hover, fade it in
$( aside_feature ).hover(function() {
$(this).find('.overlay').stop(true, true).fadeIn();
// on hover out, fade it out
}, function() {
$(this).find('.overlay').stop(true, true).fadeOut();
});
}
});