Maihan Nijat Maihan Nijat - 7 months ago 8
Javascript Question

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.

Answer

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>