Search code examples
jquerycssfadeto

Jquery fade icon back on mouseout to the value it had before mousenter


I have this code which fades some icons to opacity 1.0 on mouseenter and back to 0.3 on mouseleave. It works great except that I have since have these icons set to opacity 0.13 in a different responsive view, but the code below still fades them back to 0.3 instead of 0.13 on mouse out, which is not what I want.

$(".social-holder img").on("hover", function(e) {
    if(e.type == "mouseenter") {
        $(this).fadeTo('fast', 1.0);
    }
    else if (e.type == "mouseleave") {
        $(this).fadeTo('fast', 0.3);
    }
});

I tried the code below, and I cant understand why it wont work. It leaves the icon at 1.0 on mouseleave

$(".social-holder img").on("hover", function(e) {
    var currentOpacity = $(this).css('opacity');
    if(e.type == "mouseenter") {
        $(this).fadeTo('fast', 1.0);
    }
    else if (e.type == "mouseleave") {
        $(this).fadeTo('fast', currentOpacity);
    }
});

By the way the var currentOpacity seems to work fine, as I checked with the console, but it doesn't seem to get inside the else if statement. Maybe I have some misunderstanding about scope or something.


Solution

  • Your code doesn't work because every time the handler is called, currentOpacity changes. So on mouse leave, this code is executed:

     var currentOpacity = $(this).css('opacity');
     $(this).fadeTo('fast', currentOpacity);
    

    which is an elaborate way to do nothing :-)

    Use this code instead:

    if(e.type == "mouseenter") {
        // Either preserve the saved value or get current opacity
        var origOpacity = $(this).data('origOpacity') || $(this).css('opacity');
        $(this).fadeTo('fast', 1.0).data('origOpacity', origOpacity);
    }
    else if (e.type == "mouseleave") {
        var origOpacity = $(this).data('origOpacity');
        $(this).fadeTo('fast', origOpacity, function(){ $(this).removeAttr('style'); });
    }
    

    This saves the opacity on enter in the element's data map and gets it back from there.