SMacFadyen
SMacFadyen

Reputation: 3165

jQuery .animate() more efficient

I'm trying to make this code more efficient, so I don't have to replicate it. I have 3 boxes with the mark up:

<div class="feature purple">
</div>

<div class="feature red">
</div>

<div class="feature blue">
</div>

And I am animating their contents, which I have ommited for less spam with:

$(function(){ 
    $('.purple').hover(function() {

        $('.purple .icon').animate(
            { left: 220, opacity: 0.5 }, {
                duration: 'slow',
                easing: 'easeInOutQuart'
        });

        $('.purple .the-title').animate(
            { left: 15 }, {
                duration: 'slow',
                easing: 'easeInOutQuart'
        });

    });   
    $('.purple').mouseleave(function() {

        $('.purple .the-title').animate(
            { left: 75 }, {
            duration: 'slow',
            easing: 'easeInOutQuart'

        });
        $('.purple .icon').animate(
            { left: 5, opacity: 1 }, {
            duration: 'slow',
            easing: 'easeInOutQuart'
        });
    });              
});

How can I attach jQuery to '.feature' without the other 2 boxes animating, and lowering how many lines of jQuery I have to use?

Thanks in advance.

Upvotes: 0

Views: 80

Answers (1)

Dutchie432
Dutchie432

Reputation: 29160

Something like this should work just fine. Make sure you use mouseover instead of hover in that first binding.

$(function(){ 
    $('.feature').mouseover(function() {

        $(this).find('.icon').stop().animate(
            { left: 220, opacity: 0.5 }, {
                duration: 'slow',
                easing: 'easeInOutQuart'
        });

        $(this).find('.the-title').stop().animate(
            { left: 15 }, {
                duration: 'slow',
                easing: 'easeInOutQuart'
        });

    }).mouseleave(function() {

        $(this).find('.the-title').stop().animate(
            { left: 75 }, {
            duration: 'slow',
            easing: 'easeInOutQuart'

        });
        $(this).find('.icon').stop().animate(
            { left: 5, opacity: 1 }, {
            duration: 'slow',
            easing: 'easeInOutQuart'
        });
    });              
});

Upvotes: 1

Related Questions