0
\$\begingroup\$

I have two icon animations that pretty much do the same thing, the only difference between them is positioning... one is left and the other right.

I would like to use one block of code for both left and right icon animations.

//////////// Left Icon Animation ////////////
$('.recent .left-icon').css({opacity:0, left:33});
$('.recent .controls-wrap').hover(function() {
    $(this).find('.left-icon').stop()
        .animate({left:63}, {duration:300})
        .animate({opacity:'0.99'}, {duration:400});
},function() {
    $(this).find('.left-icon').stop()
        .animate({left:33}, {duration:550})
        .animate({opacity:'0'}, {duration:300});
});





//////////// Right Icon Animation ////////////
$('.recent .right-icon').css({opacity:0, right:33});
$('.recent .controls-wrap').hover(function() {
    $(this).find('.right-icon').stop()
        .animate({right:63}, {duration:300})
        .animate({opacity:'0.99'}, {duration:400});
},function() {
    $(this).find('.right-icon').stop()
        .animate({right:33}, {duration:550})
        .animate({opacity:'0'}, {duration:300});
});
\$\endgroup\$
1
\$\begingroup\$

Make a function with one parameter, depending on the direction (right or left), copy a block of code and replace the key word there.

\$\endgroup\$
1
\$\begingroup\$

Why don't you add a common class name, say, anim-icon to both the icons, and add a left and right class to each one of them.

Then:

$('.recent .anim-icon').each(function(){
    // thisClass will have either left or right
    var thisClass = $(this).attr('class').replace('anim-icon ',''),
    $this = $(this);
    $this.css({opacity:0, thisClass:33});
    $('.recent .controls-wrap').hover(function() {
        $this.stop()
        .animate({thisClass:63}, {duration:300})
        .animate({opacity:'0.99'}, {duration:400});
    },function() {
    $this.stop()
        .animate({thisClass:33}, {duration:550})
        .animate({opacity:'0'}, {duration:300});
    });
});
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy