Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make mouseenter, mouseleave toggle in one function

Tags:

jquery

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.

like image 234
riotgear Avatar asked Sep 27 '15 20:09

riotgear


2 Answers

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.

like image 127
duncanhall Avatar answered Nov 19 '22 04:11

duncanhall


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.

like image 5
Pierre Smith Avatar answered Nov 19 '22 06:11

Pierre Smith