JQuery switch class animation

I found this code:

$('li input:checked').click(function() { $(this).parent().parent().toggleClass("uncheckedBoxBGColor", 1000); }); 

It works well when it clicks the item for the first time. It changes the background color, but when I click it again, it is delayed for 1000ms, and then another background color flashes. I want it to be animated when it has a class, and when not, not just the first click.

+4
source share
3 answers

This is easy with CSS transitions:

JS:

 $('li input:checked').click(function() { $(this).parent().parent().toggleClass("uncheckedBoxBGColor", 1000); }); 

CSS

 .uncheckedBoxBGColor { background-color: orange; /*other properties*/ transition: background-color .3s; } 

This will add effect whenever a class is included, but when it does not have this class, then there are no transitions. Instead, you can enable this transition for ALL <LI> elements, for example:

CSS

 li { transition: background-color .3s; } 

OR for all <INPUT> elements following the <LI><INPUT> combination:

 li input { transition: background-color .3s; } 

You get it.

+1
source

The jquery.toggleClass function is not intended to fade. See http://api.jquery.com/toggleClass/ for details.

If you want to change the background color, try using the CSS3 transition function as described on the Mozilla side: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions .

+1
source

Perhaps because you are using " input:checked "

try using

  $('li input[type=checkbox]').click(function () { $(this).parent().parent().toggleClass("uncheckedBoxBGColor", 1000); }); 

it works for me.

0
source

Source: https://habr.com/ru/post/1497059/


All Articles