dvlden
dvlden

Reputation: 2462

Current class - mouseenter jQuery Animation

My brain just stuck its 4:40 AM and I don't know what to do. Either I don't have solution in my head or I should sleep.

However I don't know how to animate only currently selected/hovered class and not all of them.

Here's the HTML part:

        <div class="cardWrap">
            <div class="backlit"></div>

            <div class="cardStyle">
                <div class="cardOverlay"></div>
                <ul class="cardAmount">
                    <li>Role Gift</li>
                    <li>Download and Play <br> Your Favourite Games</li>
                    <li>$10</li>
                    <li> </li>
                </ul>
            </div>

            <a class="cardSelect">Get this amount</a>
        </div>

Here's the jQuery part:

<script>
    $(function() {
        $('.cardWrap').on('mouseenter mouseleave', function(e) {
            if(e.type === 'mouseenter') {
                $('.backlit').stop().animate({'opacity': '.9'})
            } else {
                $('.backlit').stop().animate({'opacity': '.4'})
            }
        });
    });
</script>

It works pretty fine... It reduces and increase opacity on hover of the parent. However, why it animates all of them if I have for example 3x same html structure and not only currently hovered one ?

Upvotes: 0

Views: 123

Answers (2)

Chris Barr
Chris Barr

Reputation: 34032

@jSang has the right idea, but I think this can even be simplified by using hover and fadeTo instead.

$('.cardWrap').hover(function() {
    $(this).children('.backlit').stop().fadeTo(300, '.9');
}, function(){
    $(this).children('.backlit').stop().fadeTo(300, '.4');
});

DEMO

Upvotes: 1

Sang Suantak
Sang Suantak

Reputation: 5265

Change your script to this. You need to limit the scope to the hovered element's child.

$(function () {
    $('.cardWrap').on('mouseenter mouseleave', function (e) {
        if (e.type === 'mouseenter') {
            $(this).children('.backlit').stop().animate({
                'opacity': '.9'
            })
        } else {
            $(this).children('.backlit').stop().animate({
                'opacity': '.4'
            })
        }
    });
});

Upvotes: 2

Related Questions