Maihan Nijat
Maihan Nijat

Reputation: 9344

How to toggle style in animation using jQuery?

How can I add opacity: 0.5 to li when it's clicked and toggle the opacity back to opacity:1 when clicked again with animation?

$('li').on('click', function () {
    $(this).animate({
        opacity: 0.5
    }, 500, function () {
        $(this).toggleClass('completed');
    });
});

Is there any simple solution like toggling between classes or do I need to add logic to check the current opacity and change accordingly? I don't want to change markup or CSS but would like to do it through jQuery.

Upvotes: 1

Views: 68

Answers (3)

adeneo
adeneo

Reputation: 318222

All you need is a flag

$('li').on('click', function () {

    var opacity,
        flag = $(this).data('flag');

    if ( flag ) {
        opacity = 1;
    } else {
        opacity = 0.5;
    }

    $(this).animate({
        opacity: opacity
    }, 500, function () {
        $(this).toggleClass('completed');
        $(this).data('flag', !flag);
    });
});

(Really verbose on purpose)

$('li').on('click', function () {

    var opacity,
        flag = $(this).data('flag');

    if ( flag ) {
        opacity = 1;
    } else {
        opacity = 0.5;
    }

    $(this).animate({
        opacity: opacity
    }, 500, function () {
        $(this).toggleClass('completed');
        $(this).data('flag', !flag);
    });
});
li {color : red; cursor: pointer; margin: 20px 0 0 0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li>Click to fade</li>
    <li>Click to fade</li>
    <li>Click to fade</li>
    <li>Click to fade</li>
    <li>Click to fade</li>
    <li>Click to fade</li>
</ul>

The less verbose version

$('li').on('click', function () {
    var flag = $(this).data('flag');

    $(this).fadeTo(500, flag ? 1 : 0.5, function() {
        $(this).toggleClass('completed').data('flag', !flag);
    });
});

Upvotes: 2

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

You can do it like following.

$('li').on('click', function () {
    if ($(this).is(':animated')) return; //ignore click while animating
    
    var opacity = $(this).css('opacity') == 1 ? 0.5 : 1;
        
    $(this).animate({
        opacity: opacity
    }, 500, function () {
        $(this).toggleClass('completed');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li>Click Here</li>
    <li>Click Here</li>
</ul>

Upvotes: 3

Hugo S. Mendes
Hugo S. Mendes

Reputation: 1086

We can use math for that :)

$('li').on('click', function () {
    $(this).animate({
        opacity: (0.5 / $(this).css("opacity"))
    }, 500, function () {
        $(this).toggleClass('completed');
    });
});

Upvotes: 5

Related Questions