I looked around here and found a solution, but I was wondering if there were a way to write simpler code. Basically what I created is a simple fade in, fade out hover effect for an image.
$(document).on('mouseenter','.photos div',function () {
"use strict";
$(this).find('img.nocolor').stop().animate({ 'opacity': '0' }, 800);
});
$(document).on('mouseleave','.photos div',function () {
"use strict";
$(this).find('img.nocolor').stop().animate({ 'opacity': '1' }, 800);
});
I know you can put the mouseenter,mouseleave together but I do not know how to structure the toggle function like that. Please let me know how to simplify this.
Is there a reason you want to achieve this effect with Javacscript? You can achieve exactly what you're after with pure CSS:
#an-image {
opacity: 0.2;
transition: opacity 0.8s linear;
}
#an-image:hover {
opacity: 1;
transition: opacity 0.8s linear;
}
You can see a working example here: http://jsfiddle.net/oqqx1z3k/
You can view this example to see it combined with the example you gave.
I didn't test this but I beleive you could use the .fadetoggle() function which will do what you want.
$('.photos div').on('mouseenter mouseleave',function () {
$(this).find('img.nocolor').togglefade('slow');
});
or
$('.photos div').on({
mouseenter: function() {
$(this).find('img.nocolor').stop().animate({ 'opacity': '0' }, 800);
},
mouseleave: function() {
$(this).find('img.nocolor').stop().animate({ 'opacity': '1' }, 800);
}
})
However I'm not a fan of working with toggle and mouseenter and mouseleave simply because those functions work based on mouse movement and not position based on html document.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With